Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Complex Regular Expression for a form validation

Posted on 2013-01-05
11
Medium Priority
?
1,016 Views
Last Modified: 2013-01-05
I have this form that validates with jquery & regular expressions...

...
//some code

var characterReg = /^([a-zA-Z0-9]{2,50})$/; //only letters and numbers

if ( !characterReg.test(inputValName) ){

			result.text('that\'s not a valid name!');

...
//more code

Open in new window


Now, I need a very specific validation of a field called 'NIF', wich is the identifier of a tax-paying company in my country. And I need some help to make a regular expression to use like I did in the above code.

So I found an old javascript code online that validates 'NIF':

function IsValidNIF(nif)
{
    var c;
    var checkDigit = 0;
    //Check if is not null, is numeric and if has 9 numbers
    if(nif != null && IsNumeric(nif) && nif.length == 9)
    {
        //Get the first number of NIF
        c = nif.charAt(0);
        //Check firt number is (1, 2, 5, 6, 8 or 9)
        if(c == ‘1' || c == ‘2' || c == ‘5' || c == ‘6' || c == ‘8' || c == ‘9')
        {
            //Perform CheckDigit calculations
            checkDigit = c * 9;
            var i = 0;
            for(i = 2; i <= 8; i++)
            {
                checkDigit += nif.charAt(i-1) * (10-i);
            }
            checkDigit = 11 - (checkDigit % 11);
            //if checkDigit is higher than ten set it to zero
            if(checkDigit >= 10)
                checkDigit = 0;
            //Compare checkDigit with the last number of NIF
            //If equal the NIF is Valid.            
            if(checkDigit == nif.charAt(8))
                return true;            
        }        
    }
    return false;
}

function IsNumeric(ObjVal)
{
return /^\d+$/.test(ObjVal);
}

Open in new window


So, is it possible to make a regular expression from this?

The rules are:

-must be only numbers
-must be 9 characters(numbers) long
-the first number must be 1 or 2 or 5 or 6 or 8 or 9
-the last number performs some validation(%module) that you should understand viewing the above code

Thank you.
0
Comment
Question by:joao_c
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 38746939
-must be only numbers
-must be 9 characters(numbers) long
-the first number must be 1 or 2 or 5 or 6 or 8 or 9
 characterReg = /^[125689][0-9]{8}$/

-the last number performs some validation(%module) that you should understand viewing the above code
This part would produce a more complicated regular expression than is worth it, so I'd stick to using code.
0
 

Author Comment

by:joao_c
ID: 38746981
What you mean " ...I'd stick to using code." ?

If possible let me know "how" complicated would the regex become. I don't mind if the regex is not "readable", the aproach of regex is just to cut some lines of code. Unless the regex could have some performance/other issues,. is that the case?

Thanks a lot.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38747027
I have to agree with ozo:  You're going to be attempting to reproduce modulo arithmetic via a regex. This isn't really what regex is designed for. The code approach would be much simpler. Just use ozo's suggested pattern, then add logic for the modulo check.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:joao_c
ID: 38747116
Thanks kaufed.

Then how would I add up the 2 things (regex + code) in my form?

Should be like:

...
//some code

var myRegex = /^[125689][0-9]{8}$/;

if ( myRegex.test(inputValName) ){

			// then implement other if here with the modulo% code??

...
//more code

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 38747124
What about :
String.prototype.ozo = function(i) { return this.charAt(i-1) * (10-i); }
function IsValidNIF(nif) {
	var checkDigit = 0;
	for(var i=1;i<9;i++) checkDigit += nif.ozo(i);
	return /^[125689][0-9]{8}$/.test(nif) && ((checkDigit%11 >= 21)?0:checkDigit == nif.charAt(8));
}

Open in new window

0
 

Author Comment

by:joao_c
ID: 38747156
Thanks for the reply leakim971.

That's a little scary for my modest understanding of jquery.

Where do I put that code in the current code I have??

	<script>


	function clearInput() {
		$("#myForm :input").each( function() {
			$(this).val('');
		});
	};



	$("#submitBtn").click( function() {


		var result = $('#result');
		var company = $('#myForm > #name-of-company');
		var ai = $('#myForm > #annual-income');
		var characterReg = /^([a-zA-Z0-9]{2,50})$/; //only letters and numbers
		var aiReg = /^([0-9]{3,15})$/; //only numbers
		var inputVal = ai.val();
		var inputValName = company.val();

		if ( !characterReg.test(inputValName) ){

			result.text('that\'s not a valid name!');
			company.addClass('wrong');
			

		} else if ( !aiReg.test(inputVal) ) {

			result.text('only numbers!');
			ai.addClass('wrong');
			company.removeClass('wrong');



		} else {

			$.post( $("#myForm").attr("action"), 
			$("#myForm :input").serializeArray(), 
			function(info){ result.html(info);
			});
			clearInput();
			company.removeClass('wrong');
			ai.removeClass('wrong');

		};


	});



	$("#myForm").submit( function() {
		return false;	
	});



	</script>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 38747166
There's no query here. You need to replace your current function by the one provided
0
 

Author Comment

by:joao_c
ID: 38747314
but i a working with jquery here, I am more familiar with with. Don't know how to manipulate the DOM with pure js. Can I incorporate that function in my jquery?

Thanks
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38747318
just replace your previous one, no more no less...
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 total points
ID: 38747372
Modifying your existing code:

function IsValidNIF(nif)
{
    var checkDigit = 0;
    var i = 0;
    var characterReg = /^[125689][0-9]{8}$/;
    
    if (characterReg.test(nif) {
        //Perform CheckDigit calculations
        checkDigit = nif.charAt(0) * 9;

        for(i = 2; i <= 8; i++)
        {
            checkDigit += nif.charAt(i-1) * (10-i);
        }

        checkDigit = 11 - (checkDigit % 11);

        //if checkDigit is higher than ten set it to zero
        if(checkDigit >= 10)
            checkDigit = 0;

        //Compare checkDigit with the last number of NIF
        //If equal the NIF is Valid.            
        if(checkDigit == nif.charAt(8))
            return true;
    }

    return false;
}

Open in new window


Note:  The IsNumeric shouldn't be needed anymore--at least not for this function.
0
 

Author Closing Comment

by:joao_c
ID: 38748118
Thank you, it works great.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question