Html/Javascript: Simple Form Validation on Submit

HTML/JavaScript: Simple form validation on submit

You have several errors there.

First, you have to return a value from the function in the HTML markup: <form name="ff1" method="post" onsubmit="return validateForm();">

Second, in the JSFiddle, you place the code inside onLoad which and then the form won't recognize it - and last you have to return true from the function if all validation is a success - I fixed some issues in the update:

https://jsfiddle.net/mj68cq0b/

function validateURL(url) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}

function validateForm()
{
// Validate URL
var url = $("#frurl").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
return false;
}

// Validate Title
var title = $("#frtitle").val();
if (title=="" || title==null) {
alert("Please enter only alphanumeric values for your advertisement title");
return false;
}

// Validate Email
var email = $("#fremail").val();
if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
alert("Please enter a valid email");
return false;
}
return true;
}

Validate form on submit

Given all the comments under the question, here's my suggestion for a more flexible remake:

  • Don't use IDs for your fields
  • Use an additional <label> as wrapper
  • Don't bloat HTML with useless empty <span> error elements - create them using JS
  • Use a proper addEventListener() and use its Event in the Validation function
  • Use an errors array to store all the errors during each part of the validation
  • Only at the end, if the errors Array has items in it (meaning something is invalid) - in that case use Event.preventDefault() to prevent the form being submitted.

// Utility functions:
const EL = (sel, parent) => (parent || document).querySelector(sel);
const ELS = (sel, parent) => (parent || document).querySelectorAll(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Form validation script:
const EL_form = EL("#myForm");

const validateForm = (evt) => {

// Remove old errors
ELS(".ferror", EL_form).forEach(el => el.remove());

// Prepare an array to hold your errors
const errors = [];

// Get the desired fields:

const EL_fname = EL('[name="fname"]', EL_form);
const EL_fpass = EL('[name="fpass"]', EL_form);
const EL_fcpass = EL('[name="fcpass"]', EL_form);
const EL_femail = EL('[name="femail"]', EL_form);
const EL_fphone = EL('[name="fphone"]', EL_form);

// Validation and errors:

if (EL_fname.value.trim().length <= 4) {
errors.push({name: "fname", text: "Name is too short (min 4 chars)"});
}

if (EL_fpass.value.trim().length <= 8) {
errors.push({name: "fpass", text: "Password is too short (min 8 chars)"});
}

if (EL_fpass.value !== EL_fcpass.value) {
errors.push({name: "fcpass", text: "Passwords do not match"});
}

if (!/^.+@.+\./.test(EL_femail.value)) {
errors.push({name: "femail", text: "Invalid Email address"});
}

if (EL_fphone.value.trim().replace(/\D/g, "").length <= 6) {
errors.push({name: "fphone", text: "Invalid telephone number"});
}

// Show errors:
errors.forEach(err => {
const EL_error = ELNew("span", {
className: "ferror",
textContent: err.text,
});
EL(`[name="${err.name}"]`, EL_form).closest("label").append(EL_error);
});

// Prevent Form subnit on any error
if (errors.length) {
evt.preventDefault();
}

};

EL_form.addEventListener("submit", validateForm);
form label {
display: block;
}
.ferror {
color: red;
font-weight: 700;
}
<form id="myForm">

<label>Name: <input name="fname" type="text"></label>
<label>Password: <input name="fpass" type="password"></label>
<label>Confirm Password: <input name="fcpass" type="password"></label>
<label>Email: <input name="femail" type="email"></label>
<label>Phone: <input name="fphone" type="phone"></label>
<br>
<input type="submit" class="btn" value="Submit">

</form>

Submit HTML5 Form using Javascript and validate its inputs

It appears that triggering a click on the submit button does have the correct effect: http://jsfiddle.net/e6Hf7/.

document.myForm.submitButton.click();

and in case you don't have a submit button, add an invisible one like:

<input type="submit" style="display:none" name="submitButton">

JavaScript for Form Validation

  1. call validation onSubmit of the form
  2. The field name is wrong document.forms.register.studentID.value should be document.forms.register.studentId.value
  3. Store the error messages and display in single alert instead of checking first field and return from validation. which will fail to validate other fields.

//Function to make "Full name" form element highlightedfunction focus(){    document.forms.register.fullName.focus();}

//Requirements for Form Valuesfunction validateRegistration(){ var str = []; if(document.forms.register.fullName.value==""){ str.push("You must enter your full name"); } if(document.forms.register.studentId.value==""){ str.push("You must provide student ID"); } if(!document.forms.register.email.value.match(/.+@ufv.ca$/)){ str.push("You must provide a valid ufv email"); } if(str.length > 0) { alert(str.join('\n')); return false; } else { return true; }}
<form  action="quiz.html" id="register" method="get" onSubmit="return validateRegistration()" >      <fieldset>        <legend>Registration Form</legend>        <ol>            <li class="input">                <label >Full Name</label>                <input type="text" id="fullName" name="fullName" />             </li>             <li class="input">                <label >Student ID</label>                <input type="text" id="studentId" name="studentId" />             </li>            <li class="input">                <label >Email address</label>                <input type="text" id="email" name="email"  />             </li>          </ol>          <input type="submit" value="Start Quiz" />    </fieldset></form>

How do I validate this HTML/JavaScript form onsubmit?

The easiest way to prevent the default behavior of the form submit is to have your function return false. This will stop the form from submitting.

var onSubmitHandler = function(event){
/* validate here */
return false;
};

The other (and technically better) way is to call preventDefault on the event object that is passed as a parameter to your onSubmit function. The only issue is that some older versions of IE don't support this method, so you'll need to provide a fallback for this case:

var onSubmitHandler = function(event){
/* validate here */
if(event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
};

Open A New Page After Form Validation JavaScript

Replace your eventListener to this:

form.addEventListener('submit', e => {
e.preventDefault();

validateInputs();
if(isValid1 && isValid2 && isValid3){
form.submit();
window.location("action.html");
}
});

The submit() function has to be called by the form.

Check the documentation here: https://www.w3schools.com/jsref/met_form_submit.asp

Form Validation is successful but form doesn't submit

e.preventDefault();

is preventing the form from being submitted. If you simply remove it the form will be submitted even if the pristine check fails. So what you want to do is only prevent the default behaviour (which is the form to be submitted) if the pristine check fails:

form.addEventListener('submit', function (e) 
{
var valid = pristine.validate();
// alert('Form is valid: ' + valid);

if(valid === true)
{
// alert("This works");
return true;
}
else
{
e.preventDefault();
// alert("This doesn't work");
}
});

to simplify that a little you could simply write:

form.addEventListener('submit', function (e) 
{
//if the pristine check fails, prevent the form from being submitted
if(!pristine.validate()){
e.preventDefault();
}
});


Related Topics



Leave a reply



Submit