I am trying to reuse HTML5 validation required in simple serach form (so one input). It's exactly what I need (validation message in browser's language, styling, not allowing to progress, etc.). What I missing is trimming input string so not allowing user to submit just whitespaces.
I made research already and onsubmit event seems to be too late triggered to modify anything. I can't also make any change of actual inputs, so those has to remain intact during whole process (like with classic validation).
Is there any way to solve it with vanilla HTML5 without using libs like jQuery?
Edit: Using pattern attribute is not a solution here because it has different error message than this field cannot be empty.
You could try something along the lines of
<form method = "post">
<input type = "text" required pattern=".*[^ ].*" oninvalid="setCustomValidity('Please fill out this field')"
onchange="try{setCustomValidity('')}catch(e){}"/>
<input type = "submit" />
</form>
Otherwise if you really, really need to use only the required attribute you something like this would work for you
<form method = "post">
<input type = "text" required oninput = "if(this.value.trim() == '') { this.value = '' }"/>
<input type = "submit" />
</form>
You can use onsubmit, You just need to return false if it doesn't validate
<form onsubmit="return check()">
Enter name: <input type="text" id="myinput">
<input type="submit">
</form>
<script>
function check(){
if(document.getElementById("myinput").value.trim().length ==0){
return false;
}
return true;
}
</script>
Related
If I want to prevent my form to be submitted if the fields are blank and highlight the blank fields.The code I have so far works if I try to submit when it is blank but doesnt submit if the fields are filled. I cannot seem to figure out what I am doing wrong. Please help
JavaScript code:
function CheckFields(){
if((document.getElementById('title').value=="") || (document.getElementById("textfield").value=="")){
const element = document.querySelector('form');
element.addEventListener('submit',event =>{
event.preventDefault();
alert("Fill the form to be submitted");
document.getElementById("title").style.backgroundColor=red;
document.getElementById("title").style.backgroundColor=red;
});
}
HTML:
<input name="post" type="submit" value="Post" onclick="CheckFields();">
Re-posted from: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation for the purposes of having the a static answer to this question, as the webpage may change
Using built-in form validation
One of the most significant features of HTML5 form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements. We've seen many of these earlier in the course, but to recap:
required: Specifies whether a form field needs to be filled in before the form can be submitted.
minlength and maxlength: Specifies the minimum and maximum length of textual data (strings)
min and max: Specifies the minimum and maximum values of numerical input types
type: Specifies whether the data needs to be a number, an email address, or some other specific preset type.
pattern: Specifies a regular expression that defines a pattern the entered data needs to follow.
In general that is a wrong way to validate fields, but anyhow your error is the order of the condition and form submit event. So it should be like this:
var myForm = document.querySelector('form');
var myTitle = document.getElementById('title');
var myTextfield = document.getElementById('textfield');
myForm.addEventListener('submit', event=>{
if(myTitle.value=="" || myTextfield.value==""){
alert("Fill the form to be submitted");
myTitle.style.backgroundColor=red;
myTextfield.style.backgroundColor=red;
return false;
} else {
return true;
};
});
You can add required to input fields for client-side validation. For more advanced validation, you may want to add server-side validation via a model.
See required in action:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="" required><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
You can validate a form in many ways. In Html 5 form you can add required for client side validation. You can also validate form from server side. And you can also use ajax for realtime form validation. Use focus on the field.. to highlight a field that is not filled.
I have a form that I am trying to validate using HTML 5 (and jQuery).
The form has initial values that are loaded in from a database. The users can edit the data and then submit the form. I have an input box with maxlength set to 6 but sometimes the value pulled from the DB has more than 6 characters in it. If the user doesn't do anything and just clicks submit then I want an HTML 5 validation warning. But the form just submits without a warning
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" pattern="{0,6}">
<button class="btn btn-primary" type="submit">Update</button>
</form>
I have tried adding a pattern {0,6} but this doesn't make any difference.
I don't want the form to remove characters automatically, the user must do this.
I tried using jQuery validate, but I don't think I am doing it correctly:
$(window).on("load", function() {
const $reading01 = document.querySelector('#reading01');
$reading01.validate();
}
If you normalise the <button> (ie. give it type="button" rather than type="submit") you can take advantage of the HTML5 Constraint API for Form Validation.
The HTML5 Constraint API enables you to define your own validation constraints.
Once the form validates, you can use submit() to submit the form.
Working Example:
const checkValuesForm = document.getElementById('checkValues');
checkValuesFormSubmitButton = checkValuesForm.querySelector('[data-type="submit"]');
const checkValues = (formSubmitted = false) => {
const reading01 = document.getElementById('reading01');
if (reading01.value.length > 6) {
reading01.setCustomValidity('This number cannot be more than 6 digits long');
reading01.reportValidity();
}
else {
reading01.setCustomValidity('');
if (formSubmitted === true) {
checkValuesForm.submit();
}
}
}
checkValuesFormSubmitButton.addEventListener('click', () => checkValues(true), false);
reading01.addEventListener('keyup', checkValues, false);
window.addEventListener('load', checkValues, false);
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" />
<button class="btn btn-primary" type="button" data-type="submit">Update</button>
</form>
Further Reading
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation
https://www.sitepoint.com/using-the-html5-constraint-api-for-form-validation/
you just need to display warning or prevent going further , in that case you can do your own validation by getting id and check it is empty or not.
Like Rounin says Je sus Monica said, using setCustomValidity is the cleanest way to send a message to inform of an error on a input. Still, since you are using a submit button, you can listen to your form's submit event and validate it before send the request. Also, you can use the Document.forms read only property, which returns a collection of HTMLFormElement. I like how it looks codewise, because it is very easy to understand that you are working with a form.
const form = document.forms['checkValues'];
form.addEventListener('submit', (e) => {
e.preventDefault();
const validatedInput = form.elements['reading01'];
if (validatedInput.value.length > 6) {
validatedInput.setCustomValidity("The input value cannot be longer than 6.");
return;
}
form.submit();
});
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" pattern="{0,6}">
<button class="btn btn-primary" type="submit">Update</button>
</form>
One more thing, and this is just a personal taste, when naming variables, I normally add the $ symbol for jQuery elements. So if by chance I am using a jQuery library, I can identify which variable holds a plain javascript element and which a jQuery element.
I have a basic form which contains a text field like this:
But I want to control if exist any predefined word like "Mickey", If it does not exist, I want to block submitting, like validations in registration forms. This predefined word can be anywhere in textfield like "MickeyMouse" or "MouseMickey" or "MyMickeymouse".
You could use HTML5 form validation. Simply make the field required and give it a pattern. No JS required (although you might choose a polyfill for old browsers).
Try and submit this form without matching the pattern:
<form>
<input name="myInput"
required="required"
placeholder="Must contain Mickey"
pattern=".*Mickey.*"
title="It must contain Mickey somewhere."
/>
<input type="submit" />
</form>
Also: Untested example with basic JS fallback
HTML
<input type="submit" id="button" class="button" onclick="return submitcheck();" />
Script
function submitcheck() {
if(document.getElementById("textField").value.indexOf("Mickey") > -1) {
return true;
} else {
return false;
}
}
If n is not -1 then Mickey was in the string.
Assuming you have a 'text field' DOM element somewhere:
if($(<textfield>).val().indexOf($(<inputID>).val()) > -1){
//things to be done if 'Mickey' present
}
You can do this validation on click of the submit button.
I have a HTML page containing a form. I want to make some fields "required". The problem is that I'm not using a <input type="submit"> in my form, instead, I use a Javascript function to submit the form because I need to send a Javascript variable to my server. Here is my code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="button" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
So, Even is I have the required attribute in my input but the form is still being submitted even if I don't enter anything in the input.
Here is a JSFiddle of how I want my form to behave when clicking on the button without entering anything.
Anyone knows how form.submit() is different from having an <input> of type="submit" ?
EDIT: After following user2696779's answer and doing a little modification, here's the final working code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="submit" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
if (frm.checkValidity()) {
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
}
Your current HTML input button isn't a submit type, it's a button type. The requred attribute on your input element is therefore ignored. To change this, change your button's type to submit:
<input type="submit" value="Submit">
Browsers which support the required attribute will now display a warning when the button is clicked:
JSFiddle demo.
Submitting using javascript will not trigger any validation. If you want to submit using a regular button + javascript and still have validation, you may use HTML5's checkValidity function to verify form fields, or the entire form.
For example, using JQuery:
if(!$('form')[0].checkValidity()) {
alert('not valid');
}
else {
$('form').submit();
}
See fiddle for working example: http://jsfiddle.net/8Kmck/2/
I have 2 questions:
How to check input better? I have idea:
First, make field near input.
<input type='text' name='firstname'><label id='firstnameError'></label>
Second, call js-function on input onBlur with id of input and id of this label.
<input type='text' name='firstname' id='firstname' onBlur='checkEmpty("firstname", "firstnameError");'><label id='firstnameError'></label>
And js-script:
function checkEmpty(fieldId, errorFieldId)
{
var data = document.getElementById(fieldId).value;
if (data == "")
{
document.getElementById(errorFieldId).innerHTML="Error, input something!...";
}
}
And I will just use this function on all inputs, right?
Is it correct?
How to check all inputs in form correctly?
Sure I can set type=button and onSubmit call some function, which will check all elements in this form. ~ Same function like in first question, but with 5-7 if-blocks for each input. And yes for 10 forms, I will have to write 10 functions, etc. How better do it? Seems to me, I can only send form Id/name and get childs of element. Am I correct?
Maybe another way? I use jquery on my site anyway (some ajax). Maybe it is easier to do what I want on jquery? The problem is I am not too good in js, to use jquery easily. What do you think?
If you just want to verify if some data is provided or not, you can use required attribute.
<input type="text" name="username" required>
if you are using XHTML it should be as shown below..
<input type="text" name="username" required="required">
The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome and is not supported in Internet Explorer 9 and earlier versions, or in Safari.
In case if you want to use JavaScript. You can create a javascript function which will be called on submit of the form.
<form name="search" onsubmit="return validate()" >
Name: <input type="text" name="name"/>
Age: <input type="gender" name="sex"/>
<input type="submit" name="Submit" value="Submit"/>
</form>
function validate(){
// all the code for verification
return false; // if any of the step verification step fails. Otherwise return true.
}
Source: http://www.w3schools.com/tags/att_input_required.asp
To improve on your design, it's better to use non-inline JavaScript. Try using a design like this:
var fname = document.getElementById("firstname");
var other = document.getElementById("otherid");
fname.onblur = other.onblur = function() {
checkEmpty(this.id,this.id+"Error");
}
This will give all your desired elements the same onclick function and eliminate those pesky onblur attributes.
Edit: make sure your variables are declared before you chain assignments like this, or you will yield unwanted global variables.