javascript form validation issue - javascript

for my nic input,the no. of characters should be equal to 14 which i already did and the first character should be equal to the first letter in Lastname. how am i suppose to put this validation.
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :<input type="text" name="lastname" id="lastname">
</input><br><br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[0-9]{14}" maxlength="14"></input></br></br>
<input id="submit" type="submit" name="submit" id="submit">

You can add a custom validation: JSFiddle
Code
function validateNIC() {
var nic = document.getElementById("NIC").value;
var lname = document.getElementById("lastName").value;
var valid = true;
if (nic.length != 14) {
console.log("Length must be 14 characters");
} else if (nic[0] != lname[0]) {
console.log("First Character of both input should be same");
}
else{
console.log("Valid")
}
}
<input type="text" id="lastName">
<input type="text" id="NIC" maxlength=14>
<button onclick="validateNIC()">validate</button>

try like this using charAt.
var x = 'some string';//value from first field
var y="s2324343353";//value from nic
if(x.charAt(0) == y.charAt(0)){
alert("first character is same");
}// alerts 's'

I have modified pattern to accept first character as alphanumeric. Then following function should help you validate the first character mismatch validation.
function formValidation() {
var ln = document.getElementById("lastname");
var nic = document.getElementById("NIC");
if (ln.value.substr(0, 1) != nic.value.substr(0, 1)) {
alert("NIC first character not acceptable.");
return false;
} else {
return true;
}
}
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :
<input type="text" name="lastname" id="lastname">
</input>
<br>
<br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[a-zA-Z0-9][0-9]{13}" maxlength="14"></input>
</br>
</br>
<input id="submit" type="submit" name="submit" id="submit">

function formValidation() {
var lastname = $('#lastname').val();
var NIC = $('#NIC').val();
if (lastname.charAt(0) != NIC.charAt(0)) {
return false;
}

Related

Form Validation in JQuery Mobile

I'm trying to add validation to the form I made
<fieldset>
<legend>ENTER YOUR INFORMATION HERE FOR DELIVERY</legend>
<form action="" name="deliveryform">
Name* :<input type="text" name="name" id="name">
Phone Number* : <input type="text" name="phonenumber" id="phonenumber">
<span id="warning1"></span>
Address* : <textarea name="address" id="address" required></textarea>
Email* : <input type="text" name="email" id="email">
<span id="warning2"></span>
<input type="submit" id="submitbutton" value="Submit" onsubmit=" return validation()">
</form>
</fieldset>
Javascript
function validation()
{
var name = document.getElementsByName("name").value;
var phonenumber =document.getElementsByName("phonenumber").value;
var email = document.getElementById("email").value;
var emailformat = "[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$";
if(name == ""|| null)
{
alert("Please Enter Your Name!");
return false;
}
if(isNaN (phonenumber))
{
document.getElementById("warning1").innerHTML ="Enter numbers only";
return false;
}
if(!email.match(emailformat))
{
document.getElementById("warning2").innerHTML="Please enter the correct format. Example : Abc1234#gmail.com"
return false;
}
else
{
alert("Submitted Successfully")
}
}
Nothing changed except ''Error Loading Page '' message appeared.
Did I miss something?
I thought coding in without and with Jquery in HTML is the same thing..

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

How to check calculation answer of 2 input fields before submitting form

I have a register form with 2 fields includes random int and a result input field for the answer
there's a Javascript code to check fields are not empty when submitting
I'm trying also to calculate the 2 fields and compare it with the result value
Here's the HTML :
<form method="post" id="contactForm" enctype="multipart/form-data" name="q_sign">
<input type="text" name="q_name" id="senderName"/>
<input type="text" name="q_mail" id="senderEmail" />
<input name="val1" type="text" disabled id="val1" value="php random value1" readonly="readonly" />
<input name="val2" type="text" disabled id="val2" value="php random value2" readonly="readonly" />
<input type="text" name="total" id="total" />
<input type="submit" id="sendMessage" name="sendMessage" value="Register" onClick="return check_data(this.form)" />
Javascript part :
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if(document.q_sign.q_name.value==''){
alert("please enter your name");
return false;
}else if(document.q_sign.q_mail.value==''){
alert("please enter your email");
return false;
}else if(document.q_sign.total.value!=(val1+val2)){ //Issue is here
alert("wrong answer");
return false;
}else{
return true;
}}
maybe this is your expect below
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if (document.q_sign.total.value != (eval(val1) + eval(val2))) {
alert("wrong answer");
return false;
} else {
return true;
}
}

form validation keep the information

I am trying to keep the information that you have already written even if you have an error in completing the form.Now if you have not written something correctly all the fields are cleaned and you have to start from the beginning.
This is the HTML
<form class="form" method="post" action="" name="registration" onsubmit="return formValidation()" >
<h2>Register now for free!</h2>
<label for="Fname">First name :</label>
<input type="text" name="Fname" id="Fname" placeholder="First Name">
<label for="Lname">Last name :</label>
<input type="text" name="Lname" id="Lname" placeholder="Last Name">
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="example#email.com">
<label for="password">Password :</label>
<input type="password" name="password" id="password" placeholder="******">
<label for="cpassword">Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword" placeholder="******">
<label id="gender">Gender : </label>
<input type="radio" name="sex" value="male"><span>Male</span>
<input type="radio" name="sex" value="female"><span>Female</span><br />
<input type="submit" id="submit" name="submit" value="Register">
</form>
This is the Javascript
function formValidation() {
var fName = document.getElementById("Fname").value;
var lName = document.getElementById("Lname").value;
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var cpass = document.getElementById("cpassword").value;
if (fName_validation(fName, 20, 3)) {
if (lName_validation(lName, 20, 3)) {
if (email_validation(email)) {
if (pass_validation(pass, 20, 6)) {
}
}
}
}
function fName_validation(fName, max, min) {
var check_name = /^[A-Za-z\s ]{2,20}$/;
if (!fName.match(check_name)) {
alert("First name should not be empty / length be between " + max + " to " + min);
fName.focus();
return false;
}
return true;
}
function lName_validation(lName, max, min) {
var check_name = /^[A-Za-z\s ]{2,20}$/;
if (!lName.match(check_name)) {
alert("Last name should not be empty / length be between " + max + " to " + min);
lName.focus();
return ;
}
return true;
}
function email_validation(email) {
var checkk_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (!email.match(checkk_email)) {
alert("Please enter a valid email!");
email.focus();
return ;
}
return true;
}
function pass_validation(pass, max, min) {
var check_password = /(?=.*\d)(?=.*[a-z]).{6,}/;
if (!pass.match(check_password)) {
alert("Your password should have at least one number,one letter and should be a least 6 characters!");
pass.focus();
return false;
}
if (pass !== cpass) {
alert("Password don't match!");
cpass.focus();
return false;
}
}
alert("Well Done!You successfully registered!");
return true;
}
make sure each validation method should return true or false.
please change two return ; to return false
I would not do this with JavaScript! Because HTML5 does the job for you. Therefore there are the <input> attributes required and pattern.
<input type="text" pattern="[A-Za-z]{2,20}" required="" />
The user should be informed which pattern he can use. And everything is fine.
Example

Submitting Form W/ Javascript

My javascript form validation is working correctly. I want it so that when the form is valid, it will go to a different page. I am having trouble with that part. I tried using the document object to submit it if everything is valid but its not working
Javascript:
function func(){
var first = document.getElementById('fname').value;
var last = document.getElementById('lname').value;
var email = document.getElementById('mail').value;
var phone = document.getElementById('phone').value;
var val_phone = /^\(\d{3}\)\d{3}-\d{4}$/;
var val_mail = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if ( first == "" || last == "" || email == "" || phone == "")
{
alert("Do not Leave Any Blank Answers");
return;
}
if ( phone != phone.match(val_phone) || email != email.match(val_mail) )
{
alert("Incorrect Format! \n Please Check Email and Phone Number! ");
return;
}
else {
document.forms["survey"].sumbit();
}
}
HTML:
<form id="survey" name="survey" action="SlideShow.html" method="post">
First Name:<br>
<input type="text" id="fname" name="fname" required="required"><br>
Last Name:<br>
<input type="text" id="lname" name="lname" required="required"><br>
Email:<br>
<input type="email" id="mail" name="mail" required="required"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone" required="required"><br><br>
<input type="button" value="Submit" onclick="func()">
</form>
Your else block is calling sumbit(), but the proper spelling is submit().
Additionally, I recommend getting in the habit of a strict === check as opposed to a ==.
Here's a JSFiddle with the updated and refactored code:
http://jsfiddle.net/cyeof94g/

Categories