Validating Url in Java

How to check for a valid URL in Java?

Consider using the Apache Commons UrlValidator class

UrlValidator urlValidator = new UrlValidator();
urlValidator.isValid("http://my favorite site!");

There are several properties that you can set to control how this class behaves, by default http, https, and ftp are accepted.

How to verify if a String in Java is a valid URL?

You can try to create a java.net.URL object out of it. If it is not a proper URL, a MalformedURLException will be thrown.

How can I validate a collection of string and each element as a URL?

There is no annotation that validates the field directly. The idea of a custom annotation @URL is perfectly valid, yet you have to implement the validation itself - the annotation is just a mark that "something should happen with this".

I suggest you rename @URL to @URLCollection to avoid conflict with the class java.net.URL. Start with defining the annotation. Don't forget to the annotation @Constraint (look at its documentation to learn how to define the custom validation annotation properly):

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UrlCollectionValidator.class) // will be created below
public @interface URLCollection {
String message() default "default error message";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

Then continue with the implementation of ConstraintValidator:

public class UrlCollectionValidator implements ConstraintValidator<URLCollection, Collection<String>> {

@Override
public void initialize(URLCollectionconstraint) { }

@Override
public boolean isValid(Collection<String> urls, ConstraintValidatorContext context) {
return // the validation logics
}
}

Well, that's all. Read more about this at Configuring Custom Constraints at the Spring documentation:

Each bean validation constraint consists of two parts: * A @Constraint annotation that declares the constraint and its configurable properties. * An implementation of the javax.validation.ConstraintValidator interface that implements the constraint’s behavior.

How to validate URL in java using regex?

This works:

Pattern p = Pattern.compile("(@)?(href=')?(HREF=')?(HREF=\")?(href=\")?(http://)?[a-zA-Z_0-9\\-]+(\\.\\w[a-zA-Z_0-9\\-]+)+(/[#&\\n\\-=?\\+\\%/\\.\\w]+)?");  

Matcher m = p.matcher("your url here");

Validating URLs that don't have http

Create an URI object and check if getScheme() is empty or null. If so, preprend "http://"



Related Topics



Leave a reply



Submit