HTML code for validation - javascript

HTML code for validaton of name, mobile number etc by giving error message beside the text box in red colour
if(p.length!=10) region.innerHTML="phone num must be 10 digits";
if(isNaN(p)) region.innerHTML="digits only";
I have used this type of format but not working.

if you want to use html validation try this once:
<style type="text/css">
.validationError {
border: solid 2px red;
}
.validationValid {
border: solid 2px green;
}
</style>
<form id="customerForm">
<label>
First Name:
<input id="firstName" required />
</label>
<label>
Social Security Number:
<input id="ssn" required pattern="^[0-9]{3}-[0-9]{2}-[0-9]{4}$" title="Expected pattern is ###-##-####" />
</label>
<input type="submit" />
</form>
script:
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/jquery.h5validate.js"></script>
<script type="text/javascript">
// Enable h5Validate plugin
$("#customerForm").h5Validate({
errorClass: "validationError",
validClass: "validationValid"
});
// Prevent form submission when errors
$("#customerForm").submit(function (evt) {
if ($("#customerForm").h5Validate("allValid") === false) {
evt.preventDefault();
}
});
</script>

Try following function
var phoneNumber = "(07) 1234-5678";
phoneNumber = phoneNumber.replace(/\D/g,'');
if (phoneNumber.length == 10) {
region.innerHTML = phoneNumber + ' contains 10 digits';
}
else {
region.innerHTML= phoneNumber +' does not contain 10 digits';
}

Related

form for validation and open link in same page

Here I use HTML and javascript please go through it don't want to change my whole code but just take a look.
there is an HTML file and a javascript file.
both are linked.
in a form, I am taking user name and password and checking or validating them if they are right I will let the user go to the next page or stop it there.
<!DOCTYPE html>
<html>
<head>
<title>LOGIN</title>
<style type="text/css">
#error{
color:red;
font-style: italic;
}
#success{
color:green;
font-style:italic;
}
</style>
</head>
<body>
<form method="post" onsubmit = "return(validateForm());">
Enter username : <input id='username' type='text' required>
Enter password : <input id='password' type='password' required>
<p id="error"></p>
<p id="sucess"></p>
<input type = "submit" value = "Login" />
</form>
</body>
<script type='text/javascript' src="functions.js"></script>
</html>
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
function validateForm(){
if (username == 'username' && password == 'password'){
document.getElementById('sucess').innerHTML = 'sucessful login';
return true;
}
else{
document.getElementById('error').innerHTML = 'invalid credentials';
return false;
}
}
function welcomeuser(){
document.getElementById('welcomemsg').innerHTML('Welcome ' +username);
}
Please try below solution
functions.js code as below
function validateForm(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == 'username' && password == 'password'){
document.getElementById('sucess').innerHTML = 'sucessful login';
// redirect code in page
// window.location.href = 'thankyou.html'
return false;
} else {
document.getElementById('error').innerHTML = 'invalid credentials';
return false;
}
}
Your HTML code as below
<!DOCTYPE html>
<html>
<head>
<title>LOGIN</title>
<style type="text/css">
#error{
color:red;
font-style: italic;
}
#success{
color:green;
font-style:italic;
}
</style>
<script type='text/javascript' src="functions.js"></script>
</head>
<body>
<form method="post" onsubmit="return validateForm();">
Enter username : <input id='username' type='text'>
Enter password : <input id='password' type='password'>
<p id="error"></p>
<p id="sucess"></p>
<input type = "submit" value = "Login" />
</form>
</body>
</html>
Since you are submitting the form (using type=submit) your form skips the javascript validation. A quick fix is to change:
<input type = "submit" value = "Login" />
To:
<input type = "button" value = "Login" />
And you don't need this: onsubmit = "return(validateForm());" just call the function onclick or with event listener
Of course you need to get the values from the function in order to check it,
And then after checking if inputs are correct here:
if (username == 'username' && password == 'password'){
To do whatever you want (either redirect the user of actually submitting the form using submit() method).
I modify your code little and this should work:
document.querySelector('#submit').addEventListener('click', validateForm);
function validateForm(){
var username = document.querySelector('#username').value;
var password = document.querySelector('#password').value;
if (username === 'username' && password === 'password') {
document.querySelector('#sucess').textContent = 'sucessful login';
// redirect or submit
}
else {
document.querySelector('#error').textContent = 'invalid credentials';
}
}
#error{color:red; font-style: italic; }
#success{ color:green; font-style:italic; }
<form method="post">
Enter username : <input id='username' type='text' required>
Enter password : <input id='password' type='password' required>
<p id="error"></p>
<p id="sucess"></p>
<button id="submit" type="button">Login</button>
</form>

jQuery validate URL without http:// [duplicate]

This question already has answers here:
How to make url validation without http ( or add it after validation passed )?
(3 answers)
Closed 4 years ago.
I'm trying to validate a url without http:// using jQuery validate but it's not working. I am following the mtosic's answer from here
<form id="form" method="post" action="#">
<input type="text" name="url" id="url" />
<button type="submit">Submit</button>
</form>
$.validator.addMethod('validUrl', function(value, element) {
var url = $.validator.methods.url.bind(this);
return url(value, element) || url('http://' + value, element);
}, 'Please enter a valid URL');
$("#form").validate({
rules: {
"url": {
url: "validUrl"
}
},
submitHandler: function (form) {
alert('valid form submitted');
return false;
}
});
When I type in an address like "www.google.com" I still get the invalid error.
Here's the fiddle
What is the issue? Thank you for the help
The problem is because you've defined the rule named validUrl, yet you're still setting the url rule on the element in the $.validate settings. Also note that you want to pass a boolean value to the property, not a string. Try this:
$(document).ready(function() {
$.validator.addMethod('validUrl', function(value, element) {
var url = $.validator.methods.url.bind(this);
return url(value, element) || url('http://' + value, element);
}, 'Please enter a valid URL');
$("#form").validate({
rules: {
"url": {
validUrl: true // <-- change this
}
},
submitHandler: function(form) {
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="form" method="post" action="#">
<input type="text" name="url" id="url" />
<button type="submit">Submit</button>
</form>

Form Field Submission

I have my HTML and JS, how would I use this form in my JS so if one of the fields are not entered, the form doesnt submit and shows me my original please enter all fields error
Form:
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
HTML:
<!doctype html>
<html lang="en">
<head>
<title> Forms </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="forms.js"></script>
</head>
<body>
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value=""
placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="submit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</body>
</html>
JS:
function reset(){
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function submit(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(inp1 == "" || inp2 == "" || inp3 == "")
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
}
}
change your function name submit() to another because it conflict with builtin JS function, doing onclick="submit()" is same with this.form.submit() or document.getElementById('myForm').submit();
function reset() {
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function checkSubmit() {
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if (inp1 == "" || inp2 == "" || inp3 == "") {
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
} else {
//do your code here
document.getElementById('ErrorMessage').innerHTML = "submitting form";
document.getElementById('myForm').submit();
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button {
margin-left: 10px;
}
body {
width: 80%;
margin: auto;
font-family: sans-serif;
border: 1px solid black;
}
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="https://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value="" placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="checkSubmit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
Change button type to "submit" and do validation in onsubmit event handler:
<form onsubmit="return validateMethod()" />
Move all your validation logics into validateMethod, return false if the validation is failed.
Below is an example but I think you should use a jquery lib for this:
function validateMethod(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(!inp1 || !inp2 || !inp3)
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
return false;
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
return true;
}
}
You could simply use document.getElementById('myForm').addEventListener('submit', () => submit());
But you need to change <button id="submitButton" type="button" onclick="submit()"> Submit </button> to <button id="submitButton" type="submit"> Submit </button> (as Barmar said) and you also need to close your <form> tag.
Upon button click of the submission button you can iterate over all the input fields, determine whether or not they have the attribute required and then determine whether or not their value is an empty string (!field.value)
We put this in a try/catch block so that if a field is required and does not have a value, we can break out of the forEach loop by throwing an error and displaying the message Please Enter All Required Fields
let submit = document.querySelector("button");
submit.addEventListener("click", submitFn);
function submitFn() {
try {
document.querySelectorAll("form input").forEach(function(field) {
if (field.hasAttribute("required") && !field.value) {
throw error("not all fields filled in");
}
});
alert("all required fields filled in!")
} catch {
alert("please enter all required fields");
}
}
<form>
<label>first name </label><input required/>
<br/>
<label>last name</label><input required/>
<br/>
<label>email ( not required )</label><input />
<hr>
<button type="button">submit</button>
</form>
Note: It would be better code if you changed the type of the submit button to submit and changed the event from the above code from click to submit, but I've no idea if there was a reason for your markup or not so I leave that to your discretion.

How to do validation for 10 digit mobile number Using jQuery

<div>
<span id="mobile-valid">
<i class="fa fa-check"></i>
Valid Mobile No
</span>
<span id="mobile-invalid" >
Invalid mobile No
</span>
</div>
<div>
Mobile No
</div>
<div>
<input id="mobile-num" type="text"/>
</div>
How to do validation for 10 digit mobile number Using jQuery Ajax?Only numbers are allowed cannot use characters or alphanumeric characters.So how can i use jquery Ajax to do validation.I want to show on above input box that Invalid Email .and (dont want to show alert)
This will work for you...
$(document).ready(function(){
$("#mobile-num").on("blur", function(){
var mobNum = $(this).val();
var filter = /^\d*(?:\.\d{1,2})?$/;
if (filter.test(mobNum)) {
if(mobNum.length==10){
alert("valid");
$("#mobile-valid").removeClass("hidden");
$("#folio-invalid").addClass("hidden");
} else {
alert('Please put 10 digit mobile number');
$("#folio-invalid").removeClass("hidden");
$("#mobile-valid").addClass("hidden");
return false;
}
}
else {
alert('Not a valid number');
$("#folio-invalid").removeClass("hidden");
$("#mobile-valid").addClass("hidden");
return false;
}
});
});
.hidden{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mobile">
<div class="input">
<div class="label">
<div class="label-1">
<span id="mobile-valid" class="hidden mob">
<i class="fa fa-check pwd-valid"></i>Valid Mobile No
</span>
<span id="folio-invalid" class="hidden mob-helpers">
<i class="fa fa-times mobile-invalid"></i>Invalid mobile No
</span>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<div class="label-2">
Mobile No
</div>
</div>
<div class="col-xs-9">
<input id="mobile-num" type="text" class="form-control form-change-element" />
</div>
</div>
</div>
</div>
<form action="#">
Mobile number: <input type="text" name="mobile" pattern="^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$" title="Enter Valid mobile number ex.9811111111" required>
<input type="submit">
</form>
starting with 9,8,7 you can add more as well.
you can test it using https://regex101.com/
Valid number are.
9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
0091 - 9883443344
Try this code in your jquery function
var mobileNum = $(this).val();
var validateMobNum= /^\d*(?:\.\d{1,2})?$/;
if (validateMobNum.test(mobileNum ) && mobileNum.length == 10) {
alert("Valid Mobile Number");
}
else {
alert("Invalid Mobile Number");
}
Try this code. It contains the ten digits number validation for mobile:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style type="text/css">
body
{
padding: 10px;
font-family: Arial;
Font-size: 10pt;
}
span
{
font-weight:bold;
}
.san{
height: 26px;
width: 250px;
border: 1px solid #9E9E9E;
padding: 5px;
border-radius: 5px;
margin: 10px;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$('#txtPhone').blur(function(e) {
if (validatePhone('txtPhone')) {
$('#spnPhoneStatus').html('Valid Mobil Number');
$('#spnPhoneStatus').css('color', 'green');
}
else {
$('#spnPhoneStatus').html('Invalid Mobile Number');
$('#spnPhoneStatus').css('color', 'red');
}
});
});
function validatePhone(txtPhone) {
var a = document.getElementById(txtPhone).value;
var filter = /[1-9]{1}[0-9]{9}/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
}
});//]]>
</script>
</head>
<body>
Phone Number: <input type='text' id='txtPhone' class="san" maxlength="10"/>
<span id="spnPhoneStatus"></span>
</body>
</html>
try such thing
var value = "1234567.....";
var NumberRegex = /^[0-9]*$/;
if(value.length <= 10){
if(NumberRegex.test(value)){
//do whatever you want to
}else{
alert('invalid')
}
}
Jquery validation for mobile number using regular expression
Validation include:
10 digit number only (No alphabets and No special characters)
Numbers starts from 6,7,8,9
<html>
<body>
<label>Mobile Number:</label>
<input type="text" class="form-control mobile-valid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.mobile-valid').on('keypress', function(e) {
var $this = $(this);
var regex = new RegExp("^[0-9\b]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
// for 10 digit number only
if ($this.val().length > 9) {
e.preventDefault();
return false;
}
if (e.charCode < 54 && e.charCode > 47) {
if ($this.val().length == 0) {
e.preventDefault();
return false;
} else {
return true;
}
}
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
});
</script>
</body>
</html>
For Demo Click here!
var pattern= /^[0]*(\d{9})*\s*$/;
Use this pattern only to validate Sri Lankan numbers. In above code line only validate mobile number starting with 0.

How can I change this code for email form validation to run correctly?

Here is my js. I am trying to create an email form validation and it isn't working. Every time submit is clicked it automatically sends you to google(which is where it is supposed to send you if the input is valid) even if it just blank or incorrect.
var txtEmail = document.querySelector("email");
var txtFeedback = document.querySelector('#txtFeedback');
var errorDivs = document.getElementsByClassName("error");
formReference.addEventListener('submit', onFormSubmit);
function onFormSubmit(event) {
var isValid = true;
//clear out the feedback div
txtFeedback.innerHTML = "";
//clear out the error divs
for(var i = 0; i < errorDivs.length; i++) {
errorDivs[i].innerHTML = "";
}
if ( txtEmail.value == "" || !/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txtEmail.value)){
isValid = false;
txtFeedback.innerHTML += "<p>Please enter a valid email address.</p>";
txtEmail.nextElementSibling.innerHTML = "Please enter a valid email address."
} if(!isValid) {
event.preventDefault();
}
}
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#txtFeedback {
color: #FF0000;
}
.error {
display: inline;
color: #FF0000;
}
</style>
</head>
<body>
<div id="txtFeedback"></div>
<form action="http://www.google.com" id="myForm">
<div>
<label for="email">Email:</label>
<input id="email"/>
<div class="error"></div>
</div>
<div>
<input type="submit" value="submit" id="btnSubmit" />
</div>
</form>
<script src = "js/main.js"></script>
</body>
</html>
your first line selects email elements.
change it to select element with id of email:
var txtEmail = document.querySelector("#email");
and you didn't declared formReference in your code.
I declared it like this and it works just fine.
var formReference = document.getElementById('myForm');

Categories