I have password and repeat password fields,But I want to validate passwords depending on validate regex pattern along with matching both the password fields too.
<p:outputLabel for="Password" value="Password" />
<p:password id="Password" redisplay="true"
value="#{newUserBean.newUserDTO.password}" match="RepeatPassword"
label="Password" required="true"
requiredMessage="Password is required, cannot be empty"
validatorMessage="Password and Repeat Password fields must be same" feedback="true"
promptLabel="Password should contain atleast 8 characters ,1 number and 1 special character" >
</p:password>
<p:outputLabel for="RepeatPassword" value="Repeat Password" />
<p:password id="RepeatPassword" redisplay="true"
value="#{newUserBean.newUserDTO.password}" label="RepeatPassword"
required="true"
requiredMessage="Password is required, cannot be empty" feedback="true"
promptLabel="Repeat Password should match with Password">
</p:password>
Make changes as below
<p:outputLabel for="Password" value="Password" />
<p:password id="Password" redisplay="true"
value="#{newUserBean.newUserDTO.password}"validator="#{passwordValidator.validate}"
label="Password" required="true"
requiredMessage="Password is required, cannot be empty"
validatorMessage="Password and Repeat Password fields must be same" feedback="true"
promptLabel="Password should contain atleast 8 characters ,1 number and 1 special character" >
<p:ajax event="blur" update="msgfrpassword" />
</p:password>
<p:outputLabel for="RepeatPassword" value="Repeat Password" />
<p:password id="RepeatPassword" redisplay="true"
value="#{newUserBean.newUserDTO.password}" label="RepeatPassword" validator="#{confirmPasswordValidator.validate}"
required="true"
requiredMessage="Password is required, cannot be empty" feedback="true"
promptLabel="Repeat Password should match with Password">
<p:ajax event="blur" update="msgfrpassword" />
</p:password>
Override java validator to verify regex and compare repeat password and password
PasswordValidatorBean
#Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
matcher = pattern.matcher(value.toString());
if (!matcher.matches()) {
FacesMessage msg = new FacesMessage(
new MessageProvider()
.getValue("prometheus_passwordpromptlable"));
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
If we assume you need a regex to be both suitable for running on server and client side, I can suggest this regex that
checks the password length - .{8,}
makes sure there is at least 1 digit - (?=.*[0-9].*$)
and 1 special character (please define what special character means for you, add or remove accordingly) - (?=.*[-+()[\]~!##$%^&*+}{":;'/?.><,\].*$)`
Regex:
^(?=.*[-+()[\]~!##$%^&*+}{":;'/?.><,`\\].*$)(?=.*[0-9].*$).{8,}$
Related
I have a string retrieved from the database that can contain a series of codes in either {} or [] brackets as well as plain, user entered text. For example, each of the following would be possible values:
[code]
[code1][code2]
{code}
{code1}{code2}
{code1} Some user entered text. {code2}{code3} Some more user entered text.
Etc. etc.
What I need to do using ColdFusion is extract the codes within the {} and [] brackets so I can retrieve their descriptions from a database. For example:
{code1} Some user entered text. {code2}{code3} Some more user entered text.
Would become a list similar to:
{code1}|{code2}|{code3}
Normally I could just do something like REMatch but unfortunately I'm stuck doing this on a server running ColdFusion version 4.5 (groan) so my options are limited.
I'm thinking maybe I could do some Replaces on the string to convert it into a pipe delimited list that I can then easily process but I'm not sure if there might be a more straight forward approach? I'm not even really sure what a sensible way to process this using a Replace would be.
<cfset myString = "{code1} Some user entered text {code2}{code3} More user entered text" />
<cfset myArray = listToArray(myString, "{[") />
<cfloop index="i" from="1" to="#arrayLen(myArray)#">
<cfset myArray[i] = "{" & listFirst(myArray[i], "}]") & "}" />
</cfloop>
<cfdump var="#myArray#" />
<hr>
<cfset myList = arrayToList(myArray, "|") />
<cfdump var="#myList#" />
TryCF.com Gist:
https://trycf.com/gist/6035ddc5cd3daa81bc0943f1af33323a/lucee5?theme=monokai
I have a field that a user can input first and last name to fill out my form. Sometimes, users put on their first name and that results in empty fields in my database. PLEASE keep in mind that I cannot change this method completely because this form is part of a bigger project and it is being used by other websites of my company.
This is the part of the code that i need the validation around it. I already have a validation that ensures that the filed is not empty but I need on more to ensure that the field has two items in it separated by space.
<input name="fullname" class="fullname" type="text" value="#fullname#" maxlength="150"/>
<cfif fullname eq '' and check2 eq 'check2'>
<br /><span style="color:red">*you must enter your full name</span></cfif>
The check2 eq 'check2' is checking if the form was submitted already to ensure a user submitting their data twice.
I thought of using regular expressions to do that but unfortunately I am not very familiar with how to use regx in CF9 and the documentation online through me off a bit.
I was also thinking to use "Find" or "FindOneOF", any thoughts on that?
Also, I am trying to avoid using JQ,JS etc, so please try to keep your suggestions based on CF code IF possible.
Any help or different suggestions on how to tackle this issue will be very appreciated.
No regex is needed for this. A slightly simpler solution:
<cfset form.fullname = "Dave " />
<cfif listLen(form.fullname," ") GT 1> <!--- space-delimited list, no need for trimming or anything --->
<!--- name has more than one 'piece' -- is good --->
<cfelse>
<!--- name has only one 'piece' -- bad --->
</cfif>
You could do something like this for server side validation:
<cfscript>
TheString = "ronger ddd";
TheString = trim(TheString); // get rid of beginning and ending spaces
SpaceAt = reFind(" ", TheString); // find the index of a space
// no space found -- one word
if (SpaceAt == 0) {
FullNameHasSpace = false;
// at least one space was found -- more than one word
} else {
FullNameHasSpace = true;
}
</cfscript>
<cfoutput>
<input type="input" value="#TheString#">
<cfif FullNameHasSpace eq true>
<p>found space at position #SpaceAt#</p>
<p>Your data is good.</p>
<cfelse>
<p>Did not find a space.</p>
<p>Your data is bad.</p>
</cfif>
</cfoutput>
In a managed bean I have a property of the type int.
#ManagedBean
#SessionScoped
public class Nacharbeit implements Serializable {
private int number;
In the JSF page I try to validate this property for 6 digits numeric input only
<h:inputText id="number"
label="Auftragsnummer"
value="#{myController.nacharbeit.number}"
required="true">
<f:validateRegex pattern="(^[1-9]{6}$)" />
</h:inputText>
On runtime I get an exception:
javax.servlet.ServletException: java.lang.Integer cannot be cast to java.lang.String
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
Is the regex wrong? Or are the ValidateRegex only for Strings?
The <f:validateRegex> is intented to be used on String properties only. But you've there an int property for which JSF would already convert the submitted String value to Integer before validation. This explains the exception you're seeing.
But as you're already using an int property, you would already get a conversion error when you enter non-digits. The conversion error message is by the way configureable by converterMessage attribute. So you don't need to use regex at all.
As to the concrete functional requirement, you seem to want to validate the min/max length. For that you should be using <f:validateLength> instead. Use this in combination with the maxlength attribute so that the enduser won't be able to enter more than 6 characters anyway.
<h:inputText value="#{bean.number}" maxlength="6">
<f:validateLength minimum="6" maximum="6" />
</h:inputText>
You can configure the validation error message by the validatorMessage by the way. So, all with all it could look like this:
<h:inputText value="#{bean.number}" maxlength="6"
converterMessage="Please enter digits only."
validatorMessage="Please enter 6 digits.">
<f:validateLength minimum="6" maximum="6" />
</h:inputText>
You can achieve this without regex also
To validate int values:
<h:form id="user-form">
<h:outputLabel for="name">Provide Amount to Withdraw </h:outputLabel><br/>
<h:inputText id="age" value="#{user.amount}" validatorMessage="You can Withdraw only between $100 and $5000">
<f:validateLongRange minimum="100" maximum="5000" />
</h:inputText><br/>
<h:commandButton value="OK" action="response.xhtml"></h:commandButton>
</h:form>
To validate float values:
<h:form id="user-form">
<h:outputLabel for="amount">Enter Amount </h:outputLabel>
<h:inputText id="name-id" value="#{user.amount}" validatorMessage="Please enter amount between 1000.50 and 5000.99">
<f:validateDoubleRange minimum="1000.50" maximum="5000.99"/>
</h:inputText><br/><br/>
<h:commandButton value="Submit" action="response.xhtml"></h:commandButton>
</h:form>
I have an input field taking an email address:
<h:inputText value="#{register.user.email}" required="true" />
How can I validate the entered value as a valid email address using regex in JSF 2 / PrimeFaces?
All regular expression attempts to validate the email format based on Latin characters are broken. They do not support internationalized domain names which were available since May 2010. Yes, you read it right, non-Latin characters are since then allowed in domain names and thus also email addresses.
That are thus extremely a lot of possible characters to validate. Best is to just keep it simple. The following regex just validates the email format based on the occurrence of the # and . characters.
<f:validateRegex pattern="([^.#]+)(\.[^.#]+)*#([^.#]+\.)+([^.#]+)" />
Again, this just validates the general email format, not whether the email itself is legit. One can still enter aa#bb.cc as address and pass the validation. No one regex can cover that. If the validity of the email address is that important, combine it with an authentication system. Just send some kind of an activation email with a callback link to the email address in question and let the user login by email address.
Here is how:
Using it myself...
<h:inputText id="email" value="#{settingsBean.aFriendEmail}" required="true" label="Email" validatorMessage="#{settingsBean.aFriendEmail} is not valid">
<f:validateRegex pattern="[\w\.-]*[a-zA-Z0-9_]#[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]" />
</h:inputText>
<p:message for="email" />
Daniel.
Here's my version and it works well :
<f:validateRegex pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
And i made a demo here
This one supports unicode domain names in email:
<f:validateRegex pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[\p{L}\p{M}\p{N}.-]*(\.[\p{L}\p{M}]{2,})$" />
... and this one validates email only when email is entered (email is not required field in form):
<f:validateRegex pattern="(^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[\p{L}\p{M}\p{N}.-]*(\.[\p{L}\p{M}]{2,})$)?" />
<p:inputText id="email" required="true" label="email" size="40"
requiredMessage="Please enter your email address."
validatorMessage="Invalid email format"
value="#{userBean.email}">
<f:validateRegex
pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
</p:inputText>
<p:watermark for="email" value="Email Address *" />
<p:message for="email" />
<p:commandButton value="test" style="margin:20px"
action="#{userBean.register}" ajax="false" />
i am having a code similar to this:
<h:inputText id="email" value="#{managePasswordBean.forgotPasswordEmail}"
validatorMessage="#{validate['constraints.email.notValidMessage']}"
requiredMessage="#{validate['constraints.email.emptyMessage']}"
validator="#{managePasswordBean.validateForgotPasswordEmail}"
required="true">
<f:validateRegex pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$" />
</h:inputText>
The validator in the backing bean has its own validation message generated. but it is overwritten by the validatorMessage of the inputText tag.
My Question is: how can i define a custom validator message for the validateRegex tag? I don't want to remove the validatorMessage cause then JSF is displaying an own error message containing the regex pattern and so on -> which i dont find very pretty.
Thanks for the help :)
You can't define a separate validatorMessage for each individual validator. Best what you can do is to do the regex validation in your custom validator as well, so that you can remove the validatorMessage.
Update: since version 1.3, the <o:validator> component of the JSF utility library OmniFaces allows you to set the validator message on a per-validator basis. Your particular case can then be solved as follows:
<h:inputText id="email" value="#{managePasswordBean.forgotPasswordEmail}"
required="true" requiredMessage="#{validate['constraints.email.emptyMessage']}">
<o:validator binding="#{managePasswordBean.validateForgotPasswordEmail}" message="#{validate['constraints.email.notValidMessage']}" />
<o:validator validatorId="javax.faces.RegularExpression" pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$" message="Your new custom message here" />
</h:inputText>
Unrelated to the concrete problem: these days you would be not ready for world domination as long as you still validate email addresses based on Latin characters. See also Email validation using regular expression in JSF 2 / PrimeFaces.
This worked for me.
You can write your custom messages in "validatorMessage"
<h:form id="form">
<h:outputLabel for="name">Name :</h:outputLabel>
<h:inputText id="name" value="#{editStock.name}" required="true" requiredMessage="Name field must not be empty" validatorMessage="Your name can have only Alphabets">
<f:validateRegex pattern="^[a-zA-Z]*$" />
</h:inputText><br/>
<h:message for="name" style="color:red" />
<h:commandButton value="Update" action="#{stock.update(editStock)}" style="width: 80px;"></h:commandButton>
</h:form>