Reputation: 751
Iam trying to validate inputbox for search engine in my MasterPage for which I have used custome validator, but it does not validate instead takes me to search result. By default input box has value "Name...", so on search click it searches with "Name...".
Also I have submit button on contact us page, when I hit the button the abve validation occurs, which is not related to above search functionality. ere is my code for ref.:-
<script>
function nameNull(oSrc, args) {
if (name.Value.Trim() == "Name..." || name.Value.Trim() == "") {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
</script>
<input type="text" id="name" runat="server" value="Name..." name="name" onblur="doDefault(this)" onfocus="doClear(this)" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please enter name"
ControlToValidate="name" ClientValidationFunction="nameNull"
ForeColor="#FF3300" Font-Bold="True"></asp:CustomValidator>
Upvotes: 0
Views: 133
Reputation: 6055
At first you try to access your HTML element by id. To get element you need to use document.getElementById JS method.
Then you marked input field with runat="server" attribute. This will cause that ASP.NET will render ClientID which differ from ID you specified in ASP.NET markup. So to access your element you need to use ClientID value of the server control:
<script type="text/javascript">
function nameNull(oSrc, args) {
var element = document.getElementById('<%= this.name.ClientID %>');
var value = element.value.trim();
if (value == "Name...") {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
</script>
The second point as you see is that JavaScript is case sensitive and you need to use value.trim();.
And the last: to check that element at least has value it is better to use required field validator. So your markup should be modified to be:
<input type="text" id="name" runat="server" value="Name..." name="name" />
<asp:RequiredFieldValidator ID="NameFieldRequiredFieldValidator" ErrorMessage="Please enter name" ControlToValidate="name" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please enter name" ControlToValidate="name" ClientValidationFunction="nameNull"
ForeColor="#FF3300" Font-Bold="True"></asp:CustomValidator>
Upvotes: 1
Reputation: 819
Instead of using name.Value you should you getElementsbyname["name"]/getElementsbyId["name"]. This will work.....
Upvotes: 0