Javascript Form validation not working on any fields - javascript

Below is form validation using JavaScript but it's not working.
function validate()
{
var n=document.frm.name.value();
if(!n.match(/^[a-zA-Z]+$/))
{
alert("Enter valid Name");
document.frm.name.value="";
document.frm.name.focus();
return false;
}
var b=document.frm.mob.value();
if(!b.match(/^[0-9]+$/) || b.length<10 || b.length>10)
{
alert("Enter valid Name");
document.frm.mob.value="";
document.frm.mob.focus();
return false;
}
var y=document.frm.nn.value();
if(y==null || y=="")
{
alert("Enter valid Name");
document.frm.nn.value="";
document.frm.nn.focus();
return false;
}
var z=document.frm.email.value();
if(!z.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/))
{
alert("Enter valid Name");
document.frm.email.value="";
document.frm.email.focus();
return false;
}
}
<body>
<form name="frm" action="#" method="post" onsubmit="return validate()">
Name :<input type="text" name="name"/>
Mobile No:<input type="text" name="mob" />
Not Null :<input type="text" name="nn"/>
Email Id:<input type="text" name="email"/>
<input type="submit" name="submit" value="submit"/>
</form>
</body>

First off, don't name your fields with reserved words (like "name")
Second, value is a property, not a method, so,
var b=document.frm.mob.value;
(without the brackets)

Please,place return false outside the function.
var b=document.frm.mob.value;
if(!b.match(/^[0-9]+$/) || b.length<10 || b.length>10)
{
alert("Enter valid Name");
document.frm.mob.value="";
document.frm.mob.focus();
}
var y=document.frm.nn.value;
if(y==null || y=="")
{
alert("Enter valid Name");
document.frm.nn.value="";
document.frm.nn.focus();
}
var z=document.frm.email.value();
if(!z.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/))
{
alert("Enter valid Name");
document.frm.email.value="";
document.frm.email.focus();
}
return false;
}

Instead of calling the function validate() in form tag on event onsubmit, better use it in submit button
<input type="submit" name="submit" value="submit" onClick="return validate()" />
It will work better and outputs as required.

Related

Validation with JavaScript

There are similar questions, but I can't find the way I want to check the form submit data.
I like to check the form submit data for phone number and email. I check as follows, but it doesn't work.
How can I make it correct?
<script>
function validateForm() {
var x = document.forms["registerForm"]["Email"].value;
if (x == null || x == "") {
alert("Email number must be filled out.");
return false;
}
else if(!/#./.test(x)) {
alert("Email number must be in correct format.");
return false;
}
x = document.forms["registerForm"]["Phone"].value;
if (x == null || x == "" ) {
alert("Phone number must be filled out.");
return false;
}
else if(!/[0-9]+()-/.test(x)) {
alert("Phone number must be in correct format.");
return false;
}
}
</script>
For email I'd like to check only "#" and "." are included in the email address.
For phone number, I'd like to check ()-+[0-9] and one space are only accepted for phone number, for example +95 9023222, +95-1-09098098, (95) 902321. How can I check it?
There will be another check at the server, so there isn't any need to check in detail at form submit.
Email validation
From http://www.w3resource.com/javascript/form/email-validation.php
function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
Phone number validation
From http://www.w3resource.com/javascript/form/phone-no-validation.php.
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if ((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
You can do something like this:
HTML part
<div class="form_box">
<div class="input_box">
<input maxlength="64" type="text" placeholder="Email*" name="email" id="email" />
<div id="email-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
<div class="form_box">
<div class="input_box ">
<input maxlength="10" type="text" placeholder="Phone*" name="phone" id="phone" />
<div id="phone-error" class="error-box"></div>
</div>
<div class="clear"></div>
</div>
Your script
var email = $('#email').val();
var phone = $('#phone').val();
var email_re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,3}))$/;
var mobile_re = /^[0-9]{10}$/g;
if ($.trim(email) == '') {
$('#email').val('');
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter your Email');
} else if (!email.match(email_re)) {
$('#email-error').css('display', 'block');
$('#email-error').html('Please enter valid Email');
}
if ($.trim(phone) == '') {
$('#phone').val('');
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter your Phone Number');
} else if (!phone.match(mobile_re)) {
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please enter valid Phone Number');
} else {
$('#phone-error').css('display', 'none');
$('#phone-error').html('');
}
You could of course write the validation part yourself, but you could also use one of the many validation libraries.
One widely used one is Parsley. It's very easy to use. Just include the .js and .css and add some information to the form and its elements like this (fiddle):
<script src="jquery.js"></script>
<script src="parsley.min.js"></script>
<form data-parsley-validate>
<input data-parsley-type="email" name="email"/>
</form>
HTML5 has an email validation facility. You can check if you are using HTML5:
<form>
<input type="email" placeholder="me#example.com">
<input type="submit">
</form>
Also, for another option, you can check this example.

Javascript validation on my form not working properly

I want to make a form validation using JavaScript but its not working properly. Can someone please help me?
here is my code:
JavaScript
<script type="text/javascript">
var ck_name = /^[A-z]+$/;
var ck_email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate()
{
var name = document.form.name;
var email = document.form.email;
var username = document.form.username;
var password = document.form.password;
if (!ck_name.test(name)) {
window.alert("You must enter valid Name .");
name.focus();
return false;
}
if (!ck_email.test(email)) {
window.alert("You must enter a valid email address.");
email.focus();
return false;
}
if (!ck_username.test(username)) {
window.alert("Your valid UserName does not contain any special char.");
username.focus();
return false;
}
if (!ck_password.test(password)) {
window.alert("You must enter a valid Password ");
password.focus();
return false;
}
return true;
}
</script>
HTML
<form action="#" name="form" onsubmit="return validate();">
<p>Name: <input type="text" size="25" name="name"/></p>
<p>E-mail: <input type="text" size="25" name="email"/></p>
<p>UserName: <input type="text" size="25" name="username"/></p>
<p>Password: <input type="text" size="25" name="password"/></p>
<p><input type="submit" value="Send" name="submit" />
<input type="reset" value="Reset" name="reset" /></p>
</form>
You need to get form from document here is what you should use
var name = document.forms[0].name.value;
var email = document.forms[0].email.value;
var username = document.forms[0].username.value;
var password = document.forms[0].password.value;
This will only get html element
var name=document.forms[0].name
You need to get its value.
var name=document.forms[0].name.value;
Update the js code to get the element value
var name = document.forms['form'].elements['name'].value;
var email = document.forms['form'].elements['email'].value;
var username = document.forms['form'].elements['username'].value;
var password = document.forms['form'].elements['password'].value;
You are checking input elements instead you need to check their value.
Here is the updated/working code.
function validate() {
var name = document.form.name;
var email = document.form.email;
var username = document.form.username;
var password = document.form.password;
if (!ck_name.test(name.value)) {
window.alert("You must enter valid Name .");
name.focus();
return false;
}
if (!ck_email.test(email.value)) {
window.alert("You must enter a valid email address.");
email.focus();
return false;
}
if (!ck_username.test(username.value)) {
window.alert("Your valid UserName does not contain any special char.");
username.focus();
return false;
}
if (!ck_password.test(password.value)) {
window.alert("You must enter a valid Password ");
password.focus();
return false;
}
return true;
}
You should get elements' value. I just made some changes and works properly. Try this:
var ck_name = /^[A-z]+$/;
var ck_email = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate() {
var name = document.form.name.value;
var email = document.form.email.value;
var username = document.form.username.value;
var password = document.form.password.value;
if (!ck_name.test(name)) {
window.alert("You must enter valid Name .");
name.focus();
return false;
}
if (!ck_email.test(email)) {
window.alert("You must enter a valid email address.");
email.focus();
return false;
}
if (!ck_username.test(username)) {
window.alert("Your valid UserName does not contain any special char.");
username.focus();
return false;
}
if (!ck_password.test(password)) {
window.alert("You must enter a valid Password ");
password.focus();
return false;
}
return true;
}
<form action="#" name="form" onsubmit="return validate();">
<p>Name:
<input type="text" size="25" name="name" />
</p>
<p>E-mail:
<input type="text" size="25" name="email" />
</p>
<p>UserName:
<input type="text" size="25" name="username" />
</p>
<p>Password:
<input type="text" size="25" name="password" />
</p>
<p>
<input type="submit" value="Send" name="submit" />
<input type="reset" value="Reset" name="reset" />
</p>
</form>

Can not submit a form using javascript

The hyper link as a submit button is not working.
I think the error may be this <a href="javascript:subForm('myform')">.
I don't know whether this line accept string 'myform' as parameter.
Thanks for your help.
JS
function valid(form) {
if (form.passwd1.value == "") {
alert("Please enter the password")
form.passwd1.focus()
return false
}
if (form.passwd1.value != form.passwd2.value) {
alert("Passwords do not match");
form.passwd1.focus()
form.passwd1.select()
return false
}
return true
}
function subForm(form){
if( valid(document.form)){
document.form.submit();
}
}
Form
<form action="abc.html" name="myform">
Your name: <input type="text" size="30" />
<p>Choose a password: <input type="password" name="passwd1" /></p>
<p>Verify password: <input type="password" name="passwd2" /></p>
<img src="images/submit.jpg"/>
</form>
Instead of passing the form through as a parameter just validate the fields directly in valid(), i.e.
if (myform.passwd1.value == "") ...
For getting form by formName, you should use document.forms[formName]. Your subForm function should change to:
function subForm(formName) {
var form = document.forms[formName];
if (typeof form !== 'undefined' && valid(form)) {
form.submit();
}
}

Javascript form validation needs fix

I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}

Textarea Empty check

HTML
<form name="myForm" id="myForm" onsubmit="return validate();" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="name" id="name">
<textarea name="details" id="details"></textarea>
<input type="submit">
</form>
Javascript
function validate()
{
if(document.getElementById('details').value == '')
{
alert("Please Provide Details!");
document.getElementById('details').focus();
return false;
}
else if(document.getElementById('name').value == '')
{
alert("Please Provide Name!");
document.getElementById('name').focus();
return false;
}
else
return true;
}
OR
function validate()
{
if(document.myForm.details.value == '')
{
alert("Please Provide Details!");
document.myForm.details.focus();
return false;
}
else if(document.myForm.name.value == '')
{
alert("Please Provide Name!");
document.myForm.name.focus();
return false;
}
else
return true;
}
I have seen the codes from previous Stack Overflow but as I am using these and it is not working. Will anyone help to solve check empty Value on Textarea using Javascript but not jquery.
The Reference I have used
how to check the textarea content is blank using javascript?
And
How to check if a Textarea is empty in Javascript or Jquery?
I think you may have space problem on your textarea. Use a trim function to reduce that. Here is the example following. I hope it may solve your problem.
JavaScript Add this function
function trimfield(str)
{
return str.replace(/^\s+|\s+$/g,'');
}
And your JavaScript function
function validate()
{
var obj1 = document.getElementById('details');
var obj2 = document.getElementById('name');
if(trimfield(obj1.value) == '')
{
alert("Please Provide Details!");
obj1.focus();
return false;
}
else if(trimfield(obj2.value) == '')
{
alert("Please Provide Name!");
obj2.focus();
return false;
}
else
return true;
}
OR
function validate()
{
var obj1 = document.myForm.details;
var obj2 = document.myForm.name;
if(trimfield(obj1.value) == '')
{
alert("Please Provide Details!");
obj1.focus();
return false;
}
else if(trimfield(obj2.value) == '')
{
alert("Please Provide Name!");
obj2.focus();
return false;
}
else
return true;
}
And HTML with PHP
<form name="myForm" id="myForm" onsubmit="return validate();" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="text" name="name" id="name">
<textarea name="details" id="details"></textarea>
<input type="submit">
</form>
You can use following jQuery to escape white spaces.
if($("#YourTextAreaID").val().trim().length < 1)
{
alert("Please Enter Text...");
return;
}

Categories