Validate textarea input for alphanumeric value - javascript

I want to validate textarea which is an Address field, it must contains both of letters and numbers, at least 1 number .
for example : "Laksda Adisucipto street, no 22A."
but when i just type : "Laksda Adisucipto street" (without number) it can show alert "you must enter at least 1 number"
i'm using Twitter Bootstrap and Validator.js
here's my code
HTML :
<div class="form-group col-md-12">
<label for="address" class="control-label"><span>*</span> <?php echo $this->lang->line('address');?></label>
<textarea class="form-control" id="address" rows="5" required name="address" data-error="Address is required"></textarea>
<span class="help-block with-errors"></span>
</div>
JS :
<script>
$('#address').change(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(($('#').value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
} );

Try this
$('#address').blur(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(this.value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
});
you can check it here: http://jsfiddle.net/oa6eewck/

$('#address').blur(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(this.value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
});
This function will allow only characters and numbers,it will be good for a input text field but since you are having text area "spaces" and "commas" and "periods" are expected right.
So better follow the expression follows :
$('#address').blur(function()
{
var hasNumber = this.value.match(/^[a-zA-Z0-9\s .,]+$/);
if ( hasNumber) {
return true;
} else {
alert("message");
return false;
}
});

$('#address').on('change', function () {
var hasNumber = this.value.match(/\d/);
var isAlfa = this.value.match(/^[0-9a-zA-Z]+$/);
if ( hasNumber && isAlfa ) {
return true;
} else {
alert("message");
return false;
}
});
FIDDLE

adeneo's solution is right. but I think isAlfa should have following value
var isAlfa = this.value.match(/^[A-Za-z\d(-.,) ]+/);

Related

Regular expression for email not working

I am putting validation on email field but it shows error of invalid even where the email is typed in correct format.
Screenshot
Code
<script type="text/javascript">
function formvalidate(){
var email=document.signup_form.email.value;
var check_email= RegExp("^[A-Z0-9._-]+#[A-Z0-9.-]+\.[A-Z0-9.-]+$");
if(email=="")
{
alert("cannot be empty!");
document.signup_form.email.focus();
return false;
}
else if(!check_email.test(email))
{
alert("enter valid email address!");
document.signup_form.email.focus();
return false;
}
else
{
return true;
}
}
</script>
Thanks
try this function
function validateEmail(elementValue) {
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
Please refer this fiddle : http://jsfiddle.net/gabrieleromanato/Ra85j/
1- Use this regular expressions instead
\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*
2- Change this if (!check_email.test(email)) to
if (check_email.test(email))
Try this fuction
function isEmail(inputString) {
var regExpEmail = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
try {
return regExpEmail.test(inputString.value);
}
catch (e) {
return false;
}
}
Change var check_email= RegExp("^[A-Z0-9._-]+#[A-Z0-9.-]+\.[A-Z0-9.-]+$"); to
a function like this:
function validateEmail(email) {
var 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,}))$/;
return re.test(email);
}
You regex is not correct, there are many things that you've not considered, like your regex accepts only capital letters, to include both capital and small letters you should use :
[a-zA-Z0-9]
not this :
[A-Z0-9]
You can use this regex for validating email :
/^(([^<>()\[\]\\.,;:\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,}))$/
read this for details
Source and some tests
You can use this regex for email:
RegExp('\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b', 'i')
try this example : email validation using JQuery
function validateEmail(email) {
var 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,}))$/;
return re.test(email);
}
function validate() {
$("#emailvalidate").text("");
var email = $("#email").val();
if (validateEmail(email)) {
$("#emailvalidate").text(email + " is valid");
$("#emailvalidate").css("color", "green");
} else {
$("#emailvalidate").text(email + " is not valid");
$("#emailvalidate").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>Enter an email address:</p>
<input id='email'>
<button type='submit' id='btn'>Validate</button>
</form>
<h2 id='emailvalidate'></h2>
Try this code -
function formvalidate()
{
var email = document.signup_form.email.value;
var check_email = RegExp("^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*#([a-z0-9\\-]+\\.)+[a-z]{2,6}$", 'ig');
if(email == "")
{
alert("cannot be empty!");
document.signup_form.email.focus();
return false;
}
else if(!check_email.test(email))
{
alert("enter valid email address!");
document.signup_form.email.focus();
return false;
}
else
{
return true;
}
}
<form name="signup_form">
<input type="text" name="email" value="" />
<input type="button" name="validate" value="Validate" onclick="formvalidate()"/>
</form>
I am using below regex to validate email pattern. Regex is not 100% solution to validate an email, better use email verification. Regex can help to validate format or pattern only.
Jsfiddle: DEMO
Jsfiddle: Regex check and sample email DEMO
function validateEmail(elementValue) {
document.getElementById('error').innerHTML = elementValue + ', email is incorrect';
var emailPattern = /^[a-z0-9](?:[a-z0-9]+\.)*(?!.*(?:__|\\.\\.))[a-z0-9_]+#(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9](?!$)){0,61}[a-zA-Z0-9]?)|(?:(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])))$/;
if (emailPattern.test(elementValue)) {
document.getElementById('error').innerHTML = elementValue + ', email is correct';
}
return false;
}
#error {
color: red;
font-size: 2rem;
}
input[type='email'] {
padding: 5px;
width: 300px;
border-color: blue;
font-size: 16px;
}
<form name="signup_form">
<input type="email" value="" onblur="validateEmail(this.value)">
<br />
<lable id="error"></lable>
</form>
Change your regular expression to below
^[a-zA-Z0-9._-]+#[A-Za-z0-9.-]+\.[a-zA-Z0-9.-]+$
Hope this helps :)

javascript validation phone number

alright, whats wrong with my script, JShint is throwing three lines of red code saying i have issues in my variable and my if/else statement. I am trying to validate if the phone number is a valid USA phone format
$( "#phone" ).focusout(function telephone() {
if( this.value === "" || this.value === null ) {
$( "#error_messages" ).text("");
return false;
} else {
var re = \d{3}[\-]\d{3}[\-]\d{4};
if(re.test(document.getElementById("phone").value)) {
$( "#error_messages" ).text("");
return true;
} else {
$( "#error_messages" ).text("Phone Number* not a valid format xxx-xxx-xxxx");
return false;
}
}
});
Firstly, you don't need a name for closure function. Secondly you have not enclosed regex with /..../.
var re = /\d{3}[\-]\d{3}[\-]\d{4}/;
You Should try this.
$(function(){
$("#phone").change(function telephone() {
if (this.value === "" || this.value === null) {
$("#error_messages").text("");
return false;
} else {
if (/\d{3}[\-]\d{3}[\-]\d{4}/.test($(this).val())) {
$("#error_messages").text("");
return true;
} else {
$("#error_messages").text("Phone Number* not a valid format xxx-xxx-xxxx");
return false;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" id="phone" />
<span id="error_messages"></span>
This is an expression tested on http://tools.netshiftmedia.com/regexlibrary/# for numbers. change it to /^\d{3}[\-]\d{3}[\-]\d{4}$/ in your JS code and apply regex code within /..../ in that tools
I applied
^\d{3}[\-]\d{3}[\-]\d{4}$
It's ok with your numbers :

Validation of multiple empty field

I am trying to validate two fields in my form.
But it is displaying the error message only for one field.
Following is Javascript code:
function req() {
if (document.reg_indi_form.txt_fnm.value=="") {
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
return false;
}
if (document.reg_indi_form.txt_lnm.value=="") {
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
return false;
}
}
HTML code:
<input name="txt_fnm" type="text" id="txt_fnm"/> <label id="i"></label>
<input name="txt_lnm" type="text" id="txt_lnm"/>\<label id="i1"></label>
If you need to get all errors tested, as "Disha" commented, you can not put a return statement in each if blocks.
var noError = true;
if (document.reg_indi_form.txt_fnm.value=="") {
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
noError = false;
}
if (document.reg_indi_form.txt_lnm.value=="") {
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
noError = false;
}
return noError;
That should work as you seems to want to.
Try This Code
JavaScript
`
function validate(){
var isValid = true;
if (document.reg_indi_form.txt_fnm.value=="") {
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
isValid = false;
}
if (document.reg_indi_form.txt_lnm.value=="") {
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
isValid = false;
}
return isValid;
}`

Required field validation jquery showing error message

I validated some fields in my form.. But i have some issues..If without enter fields it shows error message.. If fill out the field still error message is showing..
How to put that ?
My code
$("#Name").focus();
$("#Name").blur(function(){
var name=$('#Name').val();
if(name.length == 0){
$('#Name').after('<div class="red">Name is Required</div>');
}
else {
return true;
}
});
$("#Address").blur(function(){
var address=$('#Address').val();
if(address.length == 0){
$('#Address').after('<div class="red">Address is Required</div>');
return false;
}
else {
return true;
}
});
can anyone help me please?????
You should remove this labels after that user input some data
$("#Name").focus();
$("#Name").blur(function(){
var name=$('#Name').val();
if(name.length == 0){
$('#Name').after('<div class="red">Name is Required</div>');
}
else {
$('#Name').next(".red").remove(); // *** this line have been added ***
return true;
}
});
$("#Address").blur(function(){
var address=$('#Address').val();
if(address.length == 0){
$('#Address').after('<div class="red">Address is Required</div>');
return false;
}
else {
$('#Address').next(".red").remove(); // *** this line have been added ***
return true;
}
});
jsfiddle: DEMO
Your code has bug that it places div as many as time as you blur in empty textbox.
This bug is also removed by my code See-:
Working Demo http://jsfiddle.net/XqXNT/
$(document).ready(function () {
$("#Name").focus();
$("#Name").blur(function () {
var name = $('#Name').val();
if (name.length == 0) {
$('#Name').next('div.red').remove();
$('#Name').after('<div class="red">Name is Required</div>');
} else {
$(this).next('div.red').remove();
return true;
}
});
$("#Address").blur(function () {
var address = $('#Address').val();
if (address.length == 0) {
$('#Address').next('div.red').remove();
$('#Address').after('<div class="red">Address is Required</div>');
return false;
} else {
$('#Address').next('div.red').remove();
return true;
}
});
});
It's better if you use required attribute which does the same work with less code and better manner.
HTML5
<input type="text" name="name" required />
<input type="text" name="address" required />
Try this code (I just changed the structure and added return false) :
$("#Name").focus()
$("#Name, #Address").blur(function(){
if($(this).val().length == 0){
$(this).after('<div class="red">This field is required</div>');
} else {
$(this).next('.red').remove()
}
});
But I think the best way is to add the required attribute to your fields like this :
<input type="text" name="name" required />
<input type="text" name="address" required />
Try to remove the added html in else condition.
if(name.length == 0){
$('#Name').after('<div class="red">Name is Required</div>');
}
else {
$('.red').empty(); //here
return true;
}
And the same for $("#Address")

JSP Java Script validation not working

I wrote a java script code in a JSP page,But when i try to submit the Page, my javascript validation code is not getting fired,Could any one help me what went wrong?
Here My Code:
<html>
<center><h3>Employee Absent Report</h3></center>
<head>
<script language="javascript" type="text/javascript">
function onFormSubmit(){
var countErrors = 0;
var strDt=document.getElementById("startdate").value;
var endDt=document.getElementById("todate").value;
var flag=false;
var eFlag = false;
if (IsEmpty(strDt)==false && IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (IsEmpty(strDt)==true && IsEmpty(endDt)==false ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form" action="FormServlet" method="get" onsubmit="return onFormSubmit(); ">
<center>
<div id="formErrors" class="error"></div>
FromDate:
<input type="text" name="startdate" id="startdate"/>
<div id="divStartDate"></div>
<br>
ToDate:
<input type="text" name="todate" id="todate"/>
<div id="divExpiryDate"> </div>
<br>
<input type="submit" value="submit"/>
</center>
</form>
</body>
</html>
is there a method "IsEmpty" in javascript? I think that's the problem. If you have that defined in some other place, try running your code in Firefox and watch Error Console for errors.
Looks like a logical error to me. Try replacing this:
if (IsEmpty(strDt)==false && IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (IsEmpty(strDt)==true && IsEmpty(endDt)==false ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
with:
if (endDt.length==0) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (strDt.length==0) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
Do the validation this way
if (endDt === "") {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (strDt === "" ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
Hope this helps!
this is the working modified code
<script>
function onFormSubmit(event){
var countErrors = 0;
event.preventDefault();
var strDt=document.getElementById("startdate").value;
var endDt=document.getElementById("todate").value;
var flag=false;
var eFlag = false;
if ( IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
eFlag = true ;
}
if (IsEmpty(strDt)==true ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
eFlag = true;
}
if(eFlag)
{
return false;
}
return true;
}
function IsEmpty(input)
{
if(input.replace(/^\s+|\s+$/g,"") === "") {
return true;
}
return false;
}

Categories