I want to validate a username using Javascript. I have validated if media name is null. Now I want to check special characters are not taken except space.
<input type="text" name="medianame" id="medianame" value="" required="required">
<a class="edit" href="" id="edit" onclick="return chk_val()">Save</a>
<script>
function chk_val() {
if (document.getElementById('medianame').value == "") {
alert("Please enter name");
return false;
}
else {
return false;
}
}
</script>
You can use a regular expression to test whether a string contains only the characters you want to allow:
/^[a-z ]+$/i
...or test for characters that aren't allowed:
/[^a-z ]/i
Use the .test() method in your function as follows:
function chk_val() {
var val = document.getElementById('medianame').value;
if (val === "") {
alert("Please enter name");
return false;
} else if (/[^a-z ]/i.test(val)) {
alert("Please enter only letters or spaces");
return false;
}
return true;
}
function chk_val()
{
var error = false;
var name = document.getElementById('medianame').value;
if (name == "")
error = true;
else if( /^[A-z ]+$/.test(name) == false)
error = true;
if(error)
{
alert("Please enter correct name");
return false;
}
return true;
}
This will check for all the expressions possible. You can filter your needs from this.
var yourExp = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]+$/g;
Then you can match like
var yourStr = document.getElementById('medianame').value;
if( yourStr.match(yourExp) == True ){
alert('Matched');
}
Related
I wrote this code for validate password and i need to show user two different alerts.
(pw.length < 8) when this condition executed "Password need minimum 8 characters"
(pw != cpw) "Passwords does not match"
I already tried all if statements but it not gonna help.
<script>
function validatePassword(){
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
if((pw.length < 8)||(pw != cpw))
{
alert("please enter the correct password")
return false;
Event.preventDefault();
}
return true;
}
</script>
Does anyone know if something...
Use a boolean and two if statements. Return the boolean at the end for true or false.
function validatePassword() {
const pw = document.getElementById("txtPassword").value;
const cpw = document.getElementById("txtCPassword").value;
let isValid = true;
if (pw.length < 8) {
alert('Password is not long enough. Minimum length is 8 characters.');
isValid = false;
}
if(pw !== cpw)) {
alert('Passwords do not match'.);
isValid = false;
}
return isValid;
}
Or have both messages in one alert using an array
function validatePassword() {
const pw = document.getElementById("txtPassword").value;
const cpw = document.getElementById("txtCPassword").value;
const errors = [];
if (pw.length < 8) {
errors.push('Password is not long enough. Minimum length is 8 characters.');
}
if(pw !== cpw)) {
errors.push('Passwords do not match.');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
}
here is most basic version you can use this type of code.
function validatePassword(){
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
if((pw.length < 8))
{
alert("please enter the correct password")
return false;
} else if((cpw != pw)) {
alert("Passwords does not match")
} else {
alert("Password is correct!")
return true;
}
}
<form id="form">
<input type="text" id="txtPassword">
<input type="text" id="txtCPassword">
<input onclick="event.preventDefault();validatePassword()" type="submit" value="Submit">
</form>
This will do.
<script>
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
function validatePassword(){
if(pw.length < 8)
{
alert("Password need minimum 8 characters")
}
if(pw != cpw){
alert("Passwords does not match")
}
}
I don't think you need to show 2 alerts. When txtPassword is invalid, users have to retype both passwords whether passwords match or not. There is no point in showing "Passwords does not match" message in that case.
To know how to show 2 alerts, see my second code.
First, here is another solution:
const FORM = document.querySelector('#form');
const PSW = document.querySelector('#txtPassword');
const C_PSW = document.querySelector('#txtCPassword');
FORM.addEventListener('submit', event => {
event.preventDefault();
if (!validatePassword()) return;
console.log('Submitted');
})
function validatePassword() {
let pw = PSW.value;
let cpw = C_PSW.value;
if (pw.length < 8) {
alert('please enter the correct password');
return;
} else if (pw !== cpw) {
alert('Passwords does not match');
return;
}
return true;
}
<form action="" id="form">
<input type="password" id="txtPassword">
<input type="password" id="txtCPassword">
<input type="submit" value="Submit">
</form>
To show 2 alerts:
function validatePassword() {
let pw = PSW.value;
let cpw = C_PSW.value;
if (pw.length < 8) {
alert('please enter the correct password');
if (pw !== cpw) {
alert('Passwords does not match');
}
return;
} else if (pw !== cpw) {
alert('Passwords does not match');
return;
}
return true;
}
So I made a form in a table in html and the javascript code checks till the (creditcard.value.length) after that the code doesn't check anything
<script language="javascript" type="text/javascript">
function ispsd(form) {
var passed = false;
if (form.Fullname.value.length < 4) {
alert("Enter a valid Full Name");
} else if (form.Email.value.indexOf("#") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Email.value.indexOf(".") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Cardholder.value.length < 3) {
alert("Card Holder name is not Valid.")
} else if (form.Creditcard.value.length != 16) {
alert("Credit card number is not valid.")
} else if (isNan(form.Creditcard.value)) {
alert("Credit card number cannot contain letters.")
} else if (isNan(form.Zip.value)) {
alert("Enter a valid Postal Code.")
} else if ((form.Expyear.value) * 1 < 2021) {
alert("Credit Card has Expired.")
} else if (isNan(form.Expyear.value)) {
alert("Enter a valid Year.")
} else if (form.cvv.value.length != 3) {
alert("Enter a valid CVV.")
} else if (isNan(form.cvv.value)) {
alert("CVV cannot contain letters.")
} else {
passed = true;
}
return passed;
}
</script>
and the thing is when I moved the (form.Expyear.value) * 1 < 2021) above the (form.Creditcard.value.length != 16) the validation worked and when I tried to add all the (else if) above the Credit card check it didn't work
don't know what's the problem
if anyone can help I would be thankful
You can always use console.log() to check what the variable has
function validate(form) {
if (form.Fullname.value.length < 4) {
alert('Enter a valid Full Name');
document.form.Fullname.focus();
return false;
}
if (form.Email.value.indexOf('#') == -1 || form.Email.value.indexOf('.') == -1) {
alert('Enter a valid E-mail adress.');
document.form.Email.focus();
return false;
}
if (form.Cardholder.value.length < 3) {
alert('Card Holder name is not Valid.');
document.form.Cardholder.focus();
return false;
}
console.log(form.Creditcard.value);
if (isNaN(form.Creditcard.value)) {
alert('Credit card number cannot contain letters.');
document.form.Creditcard.focus();
return false;
}
if (form.Creditcard.value.length < 16) {
alert('Credit card number is not valid.');
document.form.Creditcard.focus();
return false;
}
if (isNaN(form.Zip.value)) {
alert('Enter a valid Full Name');
document.form.Zip.focus();
return false;
}
if (isNaN(form.Expyear.value)) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (Number(form.Expyear.value) < 2021) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (isNaN(form.cvv.value)) {
alert('CVV cannot contain letters.');
document.form.cvv.focus();
return false;
}
if (form.cvv.value.length != 3) {
alert('Enter a valid Year.');
document.form.cvv.focus();
return false;
}
return true;
}
Try to remove the * 1, not sure what's the purpose there
isNaN, and not isNan
I would also handle it differently, what you need is to return true if they pass, rather than identify errors, for example, the demo here below. For example, it will pass your test if you have more than 16 numbers since you're checking x !== 16
function validate() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("cc").value;
// If x is Not a Number or less than one or greater than 10
if (!isNaN(x) && x.length > 3 && x.length <= 16) {
text = "Input OK";
} else {
text = "Input not valid";
}
document.getElementById("error").innerHTML = text;
}
<p>Please write only numbers, from 4 to 16 maximum characters</p>
<input type="number" id="cc"/><br>
<span id="error"></span><br>
<input type="submit" onclick="validate()" />
Last but not least, this is so verbose and difficult to maintain, I strongly suggest using a library like this one https://www.npmjs.com/package/validator to handle validation, or even jQuery has .validate() useful function for beginner.
I am working on a basic web application and i want to validate some fields of it and there is some field which is not mandtory but if it is there then in should be valid like url.
so for that my code is
validate:function(attrs){
var obTobeValidate={};
var regexp = /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/g;
obTobeValidate.questionImageUrl=$("#addSolvedExampleContainer .solvedQuestionImage").val();
obTobeValidate.solutionImageUrl=$("#addSolvedExampleContainer .solvedQuestionSolutionImage").val();
obTobeValidate.videoUrl=$("#addSolvedExampleContainer .solvedQuestionVideoUrl").val();
if(!attrs.title){
alert("please mention title..");
return false;
}
if(!attrs.question){
alert("please enter the question");
return false;
}
if(!attrs.solution){
alert("please enter the solution for the question..");
return false;
}
if (obTobeValidate.questionImageUrl="" || obTobeValidate.questionImageUrl.match(regexp))
{
return true;
}
else{
alert("please enter valid url of Question");
return false;
}
if (obTobeValidate.solutionImageUrl="" || obTobeValidate.solutionImageUrl.match(regexp))
{
return true;
}
else{
alert("please enter valid url for Solution..");
return false;
}
if (obTobeValidate.videoUrl="" || obTobeValidate.videoUrl.match(regexp))
{
return true;
}
else{
alert("please enter valid url for Video..");
return false;
}
return true;
},
and after executing this code if i left the questionImageUrl blank it shows please enter valid url and url validation is not worked in other fields like videoUrl etc.
please help me out.
If the if statement you are using assignment operator(=) instead of comparator(==).
Also if the condition is valid, don't return because you need to check other fields so
validate: function (attrs) {
var obTobeValidate = {};
var regexp = /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/g;
obTobeValidate.questionImageUrl = $("#addSolvedExampleContainer .solvedQuestionImage").val();
obTobeValidate.solutionImageUrl = $("#addSolvedExampleContainer .solvedQuestionSolutionImage").val();
obTobeValidate.videoUrl = $("#addSolvedExampleContainer .solvedQuestionVideoUrl").val();
if (!attrs.title) {
alert("please mention title..");
return false;
}
if (!attrs.question) {
alert("please enter the question");
return false;
}
if (!attrs.solution) {
alert("please enter the solution for the question..");
return false;
}
if (obTobeValidate.questionImageUrl != "" && !obTobeValidate.questionImageUrl.match(regexp)) {
return false;
}
if (obTobeValidate.solutionImageUrl != "" && !obTobeValidate.solutionImageUrl.match(regexp)) {
alert("please enter valid url for Solution..");
return false;
}
if (obTobeValidate.videoUrl != "" && !obTobeValidate.videoUrl.match(regexp)) {
alert("please enter valid url for Video..");
return false;
}
return true;
}
Currently I have a piece of javascript that stops the form been submitted if the inputs are empty but I want to make the script also stop non-alphabetical characters been put in too.
Here is the script
`function checkFormWhole(){
//var theForm = document.getElementById(id);
var letters = /^[A-Za-z]+$/;
var letnums = /^[A-Za-z0-9]+$/;
var theForm = document.getElementById("bookingForm");
if (theForm.customerType.value == ""){
alert("Please choose a customer type");
return false;
}
else if (theForm.customerType.value == "nonCorp" && theForm.forename.value == "") {
alert("Please Enter A Forename");
return false;
}
else if (theForm.customerType.value == "nonCorp" && theForm.surname.value == "") {
alert("Please Enter A Surname");
return false;
}
else if (checked == 0) {
alert("Please Choose An Event To Book");
return false;
}
else if (theForm.customerType.value == "corp" && theForm.companyName.value == "") {
alert("Please Enter A Company Name");
return false;
}
where i want the validation --->
else if (theForm.customerType.value == "nonCorp" && theForm.forename.value != (letters) /*|| theForm.customerType.surname.value.match != (letters)*/) {
alert("Please Enter A Forename Containing ONLY letters");
return false;
}
}`
You need to use the pattern as below.
var str = '123456';
var str2 = 'abcdEFG';
var patt = /[^a-zA-Z]/g;
// Contains non alphabet chars
if(patt.test(str) === true) {
console.log('Your input includes invalid characters')
}
// Contains alphabet chars only
if(patt.test(str2) === false) {
console.log('Your input includes valid characters')
}
You can simplify this but the example above has enough for you to be able to add the functionality you need.
Add your example to jsfiddle and if you have any problems, people can help you easier.
I am having a hard time trying to do a correct form validation. I have Name, Email, and Phone Number fields. I implemented the validation check for all of them and when I click on the submit query, it returns email as false, but not anything else. It also will still submit the form. How do I fix this?
JSFiddle: http://jsfiddle.net/GVQpL/
JavaScript Code:
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
return false;
}
else if(fullNameV.indexOf(" ") <= fullNameV.length)
{
alert("Not a valid name");
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
return false;
}
var atpos = emailV.indexOf("#");
var dotpos = emailV.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
error = alert("You didn't enter a phone number.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (isNaN(parseInt(stripped)))
{
error = alert("The phone number contains illegal characters.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (!(stripped.length == 10))
{
error = alert("The phone number is the wrong length. Make sure you included an area code.\n");
phoneNumberV.style.background = 'Yellow';
}
return error;
}
Update your fiddle's html for the function to be called onsubmit="return validateForm()" and removed the required="required" changed your function to work, you can see it here:
http://jsfiddle.net/GVQpL/3/
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
document.forms["queryForm"]["fullName"].focus();
return false;
}
else if(fullNameV.indexOf(" ") >= fullNameV.length)
{
alert("Not a valid name");
document.forms["queryForm"]["fullName"].focus();
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
document.forms["queryForm"]["email"].focus();
return false;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailV)){
alert("Not a valid e-mail address");
document.forms["queryForm"]["email"].focus();
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
document.forms["queryForm"]["phoneNumber"].focus();
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
alert("You didn't enter a phone number.\n");
document.forms["queryForm"]["phoneNumber"].focus()
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (isNaN(parseInt(stripped)))
{
alert("The phone number contains illegal characters.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (!(stripped.length == 10))
{
alert("The phone number is the wrong length. Make sure you included an area code.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
if(!confirm('Are you sure you want to submit your DSLR query?')){
return false;
}
return true;
}