I want a script to validate "150330-073054"(Only with digit), where '-' is mandatory and can be in any place. Actually I'm not so familiar with javascript.
2 Answers
Not specific to Salesforce but.
var numberToValidate = '150330-073054';
// create array by splitting with "-"
var numbersOnly = numberToValidate.split("-");
// check if has "-"
// check if it has length of two if we spilt it by "-"
// check the first element in array is a number
// check the second element in array is a number
if(numberToValidate.indexOf('-') != -1 && numbersOnly.length==2 && isFinite(String(numbersOnly[0])) && isFinite(String(numbersOnly[1])))
{
// Number is Valid. Lets Proceed...
}
else
{
// Number is not valid. Show error
}
-
-
You're probably running into an issue with integrating it with your Visualforce page. The Javascript here works just fine for me. Ashwani's code is something that you'll need to extend to work for you.– Derek FCommented Oct 30, 2015 at 15:08
As an alternate method to Ashwani's answer, you could accomplish this with a regular expression.
In Javascript, the regex would look like this
var testString = '150330-073054';
if(testString.match(/\d+-\d+/) != null){
// String is correctly formatted
} else {
// String is not correctly formatted
}
The regex reads as follows:
- This string must have 1 or more digits (\d+, where \d means 'a digit' and + means 'one or more')
- Followed by a '-' (a hypen)
- Followed by 1 or more digits (\d+ again)
This is only a basic code fragment. You'll need to make changes as appropriate to integrate it with your Visualforce page. One example could be that you put this fragment into a function, and call the function using an inline onBlur
in an <apex:inputField>
tag like so
<apex:inputField onblur="function(this)" />
For a Javascript reference, I personally prefer Mozilla's Javascript guide
I'll leave by saying that this solution (using Javascript to validate data) is best suited for warning a user about an invalid input before they submit it. I believe that best practice is still to do final validation on the server. In your case, this could be done in your controller (or controller extension), or through a validation rule.
For validating in Apex, I'd highly recommend taking Ashwani's answer and modifying it to be written in Apex, rather than trying to use the regex functionality in Apex.